<script>
    layui.config({
        base: '/static/customAdmin/',
    }).extend({
        index: 'lib/index',
    }).use(['index', 'AutoComplete', 'laydate', 'upload'], async () => {
        const {form, admin, table, $, laydate, upload, laytpl} = layui;
        /**根据屏幕等比例缩小**/
        admin.sideFlexible_window();
        let OrderContainers = @{{.m.OrderContainers}} || [] /**集装箱**/
            , DecUsersData = @{{.m.DecUsers}} ? JSON.parse(@{{.m.DecUsers}}) : [] /**使用人**/
            , OrderDocuments = @{{.m.OrderDocuments}} || [] /**随附单证**/
            , order_id = parseInt(@{{.m.Id}}) //id
            , ieflag = "@{{.m.IEFlag}}" || "@{{.IEFlag}}" //进出口标志
            , iEFlagName = "@{{.IEFlagName}}"  //进出口标志名称
            , statusString = "@{{.m.StatusString}}" || null //状态
            , EntQualifData = @{{.m.EntQualifTypes}} ? JSON.parse(@{{.m.EntQualifTypes}}) : [] /**企业资质**/
            , OrderItemsData = @{{.m.OrderItems}} || [] /**表体**/
            , OrderItemGoodsAttr = [] /**表体货物属性**/
            , OrderItemGoodsAttrName = []  /**表体货物属性名称**/
            //  检验检疫货物规格 临时数据
            , OrderItemStuff
            , OrderItemProdValidDt
            , OrderItemProdQgp
            , OrderItemEngManEntCnm
            , OrderItemGoodsSpec
            , OrderItemGoodsModel
            , OrderItemGoodsBrand
            , OrderItemProduceDate
            , OrderItemProdBatchNo

            // 危险货物信息
            , OrderItemNoDangFlag
            , OrderItemNoDangFlagName
            , OrderItemDangName
            , OrderItemUnCode
            , OrderItemDangPackType
            , OrderItemDangPackTypeName
            , OrderItemDangPackSpec
            , OrderItemDangPackSpecName

            //货物申报产品资质
            , OrderItemLimits = []

            , SpecDeclFlag = @{{.m.SpecDeclFlag}} ? JSON.parse(@{{.m.SpecDeclFlag}}) : [] //特许业务标识
            , DecRequestCertsData = @{{.m.DecRequestCerts}} ? JSON.parse(@{{.m.DecRequestCerts}}) : []//检验检疫申报要素
            , order_note_data /**附注数据**/
            , DeclaratioMaterialCode = @{{.m.DeclaratioMaterialCode}}   /**企业承诺**/
            , isSaved = false //是否保存数据
            , orderItemIndex = null // 表体当前数据下标
            , GoodsAttrBatchData = [] // 批量修改货物属性
            , isOrderItemInsert = false; //插入数据标志

        OrderItemsData.sort(function (a, b) {  // 排序表体
            return a.GNo - b.GNo;
        });
        admin.getOrderTable(OrderItemsData, ieflag); //表体
        renderContainerTable(); //集装箱
        renderDocTable(); // 随附单证table
        // 加载按钮
        admin.getBtnTem("#order_button_template", "#order_button", {
            statusString: statusString,
            jq: $,
        });

        // 基础参数版本
        await admin.getClearanceData();
        /** 基础参数加载 */
        await admin.clearance_data_auto([
            'entry_clearance',
            'mode_shipping',
            'objectives_based',
            'nature_exemption',
            'country_area',
            'harbour',
            'terms_delivery',
            'cost_tag',
            'currency',
            'kind_packages',
            'domestic_ports',
            'inspection_quarantine',
            'related_reasons',
            'unit_measurement',
            'origin_area',
            'domestic_area',
            'destination',
            'exempting_method',
            'use',
            'type_container',
            'documents_attached',
            'enterprise_product',
            'site_code',
            'types_customs',
            'lcl_flag',
            'ann_two_account_manual',
        ])

        /**回车键光标跳转**/
        admin.keydown_input_textarea()
        /**首次进入自动聚焦 and 初始数据赋值**/
        admin.transModeControl(ieflag, isCreate())
        /**光标进入全选**/
        $('body').on('focus', 'input,textarea', function (e) {
            $(this).select()
            let tipText = ''
            for (let item of admin.tipsJson) {
                if (item.id == this.id) {
                    tipText = item.name
                    break
                }
            }
            $('#tipsMessagetext').text(tipText)
        })

        // 数据反填
        if (order_id) {
            let orderData = @{{.m}}
            for (let item in orderData) {
                // 业务选项 反填
                if (item == 'PromiseItmes' && orderData[item]) {
                    let promiseItmes = JSON.parse(orderData[item])
                    $(`input[name='PromiseItmes[]']`).each(function (index, element) {
                        for (let pItem in promiseItmes) {
                            if (index == pItem) {
                                if (promiseItmes[pItem] == '1') {
                                    $(this).next('div').click()
                                } else if (promiseItmes[pItem] == '0') {
                                    $(this).data('first', 1)
                                    $(this).prev('span').text('否')
                                }
                            }
                        }
                    })
                } else if (item == 'Type' && !orderData[item]) { // 业务事项 自报自缴 反填
                    if (!orderData[item] || orderData[item] != 'Z') {
                        $(`input[name='Type[]']`).each(function (index, element) {
                            if (index == 1) {
                                $(this).next('div').click()
                            }
                        })
                    }
                } else if (item == 'OrigBoxFlag' && orderData[item] == 1) { // 原箱运输 反填
                    $(`input[name='OrigBoxFlag']`).each(function (index, element) {
                        $(this).next('div').click()
                    })
                } else if (item == 'IsOther' && orderData[item]) { // 异地报关 反填
                    if (!($('input[name=\'IsOther\']').prop('checked'))) {
                        $('input[name=\'IsOther\']').next('div').click()
                    }
                } else if (item == 'SpecDeclFlag' && orderData[item]) { // 特殊业务标识 反填
                    let SpecDeclFlagNameData = []
                    admin.SpecDeclFlagData.forEach((value, index) => {
                        if (SpecDeclFlag[index] == '1') {
                            SpecDeclFlagNameData.push(value)
                        }
                    })
                    $('#SpecDeclFlag').val(SpecDeclFlagNameData.join(','))
                } else if (item == 'DecRequestCerts' && orderData[item]) { // 所需单证 反填
                    if (DecRequestCertsData.checkData) {
                        const data = DecRequestCertsData.checkData.map(item => item.AppCertName)
                        $('#DecRequestCerts').val(data.join(','))
                    }
                    DecRequestCertsData.checkData = DecRequestCertsData.checkData
                    DecRequestCertsData.DomesticConsigneeEname = DecRequestCertsData.DomesticConsigneeEname
                    DecRequestCertsData.OverseasConsignorCname = DecRequestCertsData.OverseasConsignorCname
                    DecRequestCertsData.OverseasConsignorAddr = DecRequestCertsData.OverseasConsignorAddr
                    DecRequestCertsData.CmplDschrgDt = DecRequestCertsData.CmplDschrgDt
                } else if (item == 'EntQualifTypes' && orderData[item]) { // 企业资质 反填
                    if (EntQualifData.length > 0) {
                        EntQualifData.forEach((value, index) => {
                            value.index = index + 1
                        })
                        $('#EntQualifTypeCode').val(EntQualifData[0].EntQualifTypeCode)
                        $('#EntQualifTypeName').val(EntQualifData[0].EntQualifTypeName)
                    }

                } else if (item == 'DeclaratioMaterialCode' && orderData[item]) { // 企业承诺 反填
                    // 企业承诺
                    if (DeclaratioMaterialCode == '') {
                        $('#DeclaratioMaterialCode').next('div').click()
                    }
                } else if (item == 'DecUsers' && orderData[item]) { // 使用人 反填
                    DecUsersData.forEach((value, index) => {
                        value.index = index + 1
                    })
                } else if (item == 'IEDate') { // 进出口日期 反填
                    if (orderData[item]) {
                        $(`#${item}`).val(orderData[item])
                    } else {
                        $(`#${item}`).val(admin.getCurrDate())
                    }
                } else if (item == 'AplDate') { // 申报日期 反填
                    if (orderData[item]) {
                        $(`#${item}`).val(orderData[item])
                    } else {
                        $(`#${item}`).val(admin.getCurrDate())
                    }
                } else if (item == 'CustomMaster') { // 申报地海关 反填
                    if (orderData[item]) {
                        $(`#${item}`).val(orderData[item])
                    } else {
                        $(`#${item}`).val(5207)
                    }
                } else if (item == 'CustomMasterName') { // 申报地海关 反填
                    if (orderData[item]) {
                        $(`#${item}`).val(orderData[item])
                    } else {
                        $(`#${item}`).val('凤岗海关')
                    }
                } else {
                    $(`#${item}`).val(orderData[item])
                }
            }
        } else {
            $(`#IEDate`).val(admin.getCurrDate())
            $(`#AplDate`).val(admin.getCurrDate())
            $(`#CustomMasterName`).val('凤岗海关')
            $(`#CustomMaster`).val(5207)
        }
        setOrderItemEmptyData(false)
        /**table点击行选中**/
        admin.table_radio_click()
        /**table左右拖动**/
        admin.table_mousedown()
        /**合同备案号列表搜索**/
        $('body').on('input', '#manual_no_search', async function () {
            const text = $(this).val()
            const data = await admin.get(`/order/account_manual?search=${text}`)
            table.reload('manual_no_list_table', {
                data: data,
            })
        })

        /**选择其他包装**/
        $('body').on('click', '#PackageInfoBtn', async function () {
            layer.open({
                type: 1,
                title: '编辑其他包装信息',
                shadeClose: true,
                area: admin.screen() < 2 ? ['80%', '300px'] : ['910px', '730px'],
                content: $('#other_packs_list').html(),
                success: function (layero, index) {
                    this.enterEsc = function (event) {
                        if (event.keyCode === 13) {
                            $('#other_packs_save').click()
                            return false
                        }
                    }
                    $(document).on('keydown', this.enterEsc)
                },
                end: function () {
                    $('#GrossWet').focus()
                    $(document).off('keydown', this.enterEsc)
                },
            })

            const data = layui.data('orderClearance').data[2]
            data.forEach(function (item, index) {
                item.index = index
            })
            table.render({
                elem: '#other_packs_list_table'
                , toolbar: true
                , defaultToolbar: ['filter']
                , colFilterRecord: 'local'
                , cols: [
                    [
                        {type: 'checkbox'}
                        , {type: 'numbers', title: '序号'}
                        , {field: 'CustomsCode', title: '包装材料种类代码'}
                        , {field: 'Name', title: '包装材料种类名称'},
                    ],
                ]
                , data: data
                , limit: data.length
                , height: 550,
            })

            $(`.layui-table-view[lay-id='other_packs_list_table'] .layui-table-body tr input`).each(function (index, el) {
                el.checked = false
            })

            if ($('#DecOtherPacks').val() && $('#DecOtherPacks').val() != 'null') {
                const dec_other_packs_data = JSON.parse($('#DecOtherPacks').val())
                for (let dec_item of dec_other_packs_data) {
                    for (let data_item of data) {
                        if (dec_item.PackType == data_item.CustomsCode) {
                            $(`.layui-table-view[lay-id='other_packs_list_table'] .layui-table-body tr[data-index=${data_item.index}] .layui-form-checkbox`).click()
                        }
                    }
                }
            }
            form.render('checkbox')
        })

        /**保存其他包装**/
        $('body').on('click', '#other_packs_save', function () {
            const checkStatus = table.checkStatus('other_packs_list_table')
            let data = []
            for (let item of checkStatus.data) {
                data.push({
                    PackQty: '0',
                    PackType: item.CustomsCode,
                    PackTypeName: item.Name,
                })
            }
            $('#DecOtherPacks').val(JSON.stringify(data))
            layer.closeAll()
        })

        /**填写备注**/
        $('body').on('click', '#NoteSOpen', async function () {
            layer.open({
                type: 1,
                title: '备注',
                shadeClose: true,
                area: admin.screen() < 2 ? ['80%', '300px'] : ['800px', 'auto'],
                content: $('#note_s_template').html(),
                success: function (layero, index) {
                    this.enterEsc = function (event) {
                        if (event.keyCode === 13) {
                            $('#note_s_save').click()
                            return false
                        }
                    }
                    $(document).on('keydown', this.enterEsc)
                },
                end: function () {
                    $(document).off('keydown', this.enterEsc)
                    let value = $('#NoteS').val()
                    $('#NoteS').val('').focus().val(value)
                },
            })
            $('#note_s_fu').focus()
            $('#note_s_fu').val($('#NoteS').val())
        })
        $('body').on('input', '#note_s_fu', function () {
            $('.note_s_fu_number').text($(this).val().length)
        })
        /**保存备注**/
        $('body').on('click', '#note_s_save', function () {
            $('#NoteS').val($('#note_s_fu').val())
            layer.closeAll()
        })

        /**标记唛码**/
        $('body').on('input', '#MarkNo', function () {
            $('.mark_no_number span').text($(this).val().length)
        })
        /**填写标记唛码**/
        $('body').on('click', '#MarkNoOpen', async function () {
            layer.open({
                type: 1,
                title: '标记唛码',
                shadeClose: true,
                area: admin.screen() < 2 ? ['80%', '300px'] : ['800px', 'auto'],
                content: $('#mark_no_template').html(),
                success: function (layero, index) {
                    this.enterEsc = function (event) {
                        if (event.keyCode === 13) {
                            $('#mark_no_save').click()
                            return false
                        }
                    }
                    $(document).on('keydown', this.enterEsc)
                },
                end: function () {
                    $(document).off('keydown', this.enterEsc)
                    let value = $('#MarkNo').val()
                    $('#MarkNo').val('').focus().val(value)
                },
            })
            $('#mark_no_fu').focus()
            $('#mark_no_fu').val($('#MarkNo').val())
            $('.mark_no_fu_number').text($('#MarkNo').val().length)
        })

        $('body').on('input', '#mark_no_fu', function () {
            $('.mark_no_fu_number').text($(this).val().length)
        })

        /**保存标记唛码**/
        $('body').on('click', '#mark_no_save', function () {
            $('#MarkNo').val($('#mark_no_fu').val())
            $('.mark_no_number span').text($('#mark_no_fu').val().length)
            layer.closeAll()
        })

        /**标记唛码回车跳转商品焦点**/
        $('body').on('keyup', '#mark_no', function (event) {
            const eCode = event.keyCode ? event.keyCode : event.which ? event.which : event.charCode
            if (event.shiftKey != 1 && eCode == 13) {
                if ($('#non-disabled-btn').attr('isdeclistshow') == 0) {
                    if ($('#ContrItem').is(':disabled')) {
                        $('#CodeTS').focus()
                    } else {
                        $('#ContrItem').focus()
                    }
                }
            }
        })

        /**检验检疫申报信息 收缩切换**/
        $('#non-disabled-btn').click(function () {
            let iTag = $(this).find('i')
            if (iTag.hasClass('transform_xia')) {
                $(this).attr('isDecListShow', '1')
                iTag.removeClass('transform_xia')
                $(this).parent().parent().nextAll().show()
                $('#OrgCodeName').attr('lay-verify', 'required')
                $('#VsaOrgCodeName').attr('lay-verify', 'required')
                $('#DespDate').attr('lay-verify', 'required')
                $('#InspOrgName').attr('lay-verify', 'required')
                $('#PurpOrgName').attr('lay-verify', 'required')
            } else {
                $(this).attr('isDecListShow', '0')
                iTag.addClass('transform_xia')
                $(this).parent().parent().nextAll().hide()
                $('#OrgCodeName').removeAttr('lay-verify')
                $('#VsaOrgCodeName').removeAttr('lay-verify')
                $('#DespDate').removeAttr('lay-verify')
                $('#InspOrgName').removeAttr('lay-verify')
                $('#PurpOrgName').removeAttr('lay-verify')
            }
        })

        // 报检信息录入
        $('#decListShow').click(function () {
            let iTag = $(this).find('i')
            if (iTag.hasClass('transform_xia')) {
                $(this).attr('isDecListShow', '1')
                iTag.removeClass('transform_xia')
                $(this).parent().parent().nextAll().show()
                $('#PurposeName').attr('lay-verify', 'required')
            } else {
                $(this).attr('isDecListShow', '0')
                iTag.addClass('transform_xia')
                $(this).parent().parent().nextAll().hide()
                $('#PurposeName').removeAttr('lay-verify')
            }
        })

        /**编辑企业资质信息**/
        let ent_qualif_index = null;
        $('body').on('click', '#EnterpriseBtn', async function () {
            layer.open({
                type: 1,
                title: '编辑企业资质信息',
                shadeClose: true,
                area: admin.screen() < 2 ? ['80%', '300px'] : ['910px', '530px'],
                content: $('#ent_qualif_template').html(),
            })
            $('#EntQualifTypeNameTem').focus()
            form.render('checkbox')

            table.render({
                elem: '#EntQualifTable'
                , toolbar: '#ent_qualif_tool'
                , defaultToolbar: ['filter']
                , colFilterRecord: 'local'
                , cols: [
                    [
                        {type: 'checkbox'}
                        , {type: 'numbers', title: '序号'}
                        , {field: 'EntQualifTypeCode', title: '企业资质类别代码'}
                        , {field: 'EntQualifTypeName', title: '企业资质类别名称'}
                        , {field: 'EntQualifNo', title: '企业资质编号'},
                    ]]
                , data: EntQualifData
                , limit: EntQualifData.length
                , height: 350,
            });

            let enterprise_product = {
                dataType: 'orderClearance',
                type: 13,
                name: '企业产品许可类别代码',
                filter_type: 's',
                id: ['#EntQualifTypeNameTem'],
                after: ['#EntQualifTypeCodeTem'],
            };
            await admin.base_clearance_data_auto(enterprise_product)
        });

        /**编辑企业资质信息--点击行反填数据**/
        table.on('row(EntQualifTable)', function (obj) {
            $('#EntQualifTypeCodeTem').val(obj.data.EntQualifTypeCode);
            $('#EntQualifTypeNameTem').val(obj.data.EntQualifTypeName);
            $('#EntQualifNoTem').val(obj.data.EntQualifNo);
            ent_qualif_index = obj.tr.data("index");
        });

        /**编辑企业资质信息--保存**/
        form.on('submit(ent_qualif_submit)', async (data) => {
            delete data.field.layTableCheckbox;
            if (ent_qualif_index != null) {
                EntQualifData.splice(ent_qualif_index, 1, data.field)
            } else {
                let EntQualifTypeCodes = EntQualifData.map(item => item.EntQualifTypeCode);
                if ($.inArray(data.field.EntQualifTypeCode, EntQualifTypeCodes) >= 0) {
                    return layer.msg('企业资质已存在')
                }
                EntQualifData.push(data.field)
            }
            ;
            table.reload('EntQualifTable', {
                data: EntQualifData,
                limit: EntQualifData.length,
            });
            $('#EntQualifTypeCodeTem').val('');
            $('#EntQualifTypeNameTem').val('');
            $('#EntQualifNoTem').val('');
            $('#EntQualifTypeCode').val(EntQualifData[0].EntQualifTypeCode);
            $('#EntQualifTypeName').val(EntQualifData[0].EntQualifTypeName);
            $('#EntQualifTypeNameTem').focus();
            ent_qualif_index = null;
        });

        /**编辑企业资质信息--删除**/
        table.on('toolbar(EntQualifTable)', function (obj) {
            let checkStatus = table.checkStatus(obj.config.id);
            let checkData = checkStatus.data;
            switch (obj.event) {
                case 'add':
                    $('#EntQualifTypeCodeTem').val('');
                    $('#EntQualifTypeNameTem').val('');
                    $('#EntQualifNoTem').val('');
                    $('#EntQualifTypeNameTem').focus();
                    ent_qualif_index = null
                    break;
                case 'delete':
                    if (ent_qualif_del_indexs.length === 0) {
                        return layer.msg('请选择数据')
                    }
                    layer.confirm('真的删除么', {title: '提示'}, async (index) => {
                        let checkEntQualifTypeCodes = checkData.map(item => item.EntQualifTypeCode);
                        let newEntQualifData = [];
                        EntQualifData.forEach(function (item, index) {
                            if ($.inArray(item.EntQualifTypeCode, checkEntQualifTypeCodes) < 0) {
                                newEntQualifData.push(item)
                            }
                        });

                        table.reload('EntQualifTable', {
                            data: newEntQualifData,
                            limit: newEntQualifData.length,
                        });

                        $('#EntQualifTypeCode').val('');
                        $('#EntQualifTypeName').val('');
                        $('#EntQualifTypeCodeTem').val('');
                        $('#EntQualifTypeNameTem').val('');
                        $('#EntQualifNoTem').val('');
                        $('#EntQualifTypeNameTem').focus();
                        ent_qualif_index = null;

                        layer.close(index)
                    });
                    break
            }
        });

        /**编辑企业资质信息--按enter保存**/
        $('body').on('keyup', '#EntQualifNoTem', function (event) {
            if (event.keyCode == 13) {
                $('#ent_qualif_submit').click();
                $('#EntQualifTypeNameTem').focus()
            }
        })

        /**编辑企业资质信息--左移**/
        $('#EnterpriseUpBtn').click(function () {
            let entQualifSeq = $('#EntQualifSeq').val();
            if (!entQualifSeq) {
                entQualifSeq = 0
            }
            if (EntQualifData.length > 0) {
                if (parseInt(entQualifSeq) < 1) {
                    layer.msg('此为第一条记录')
                } else {
                    $('input[id=\'EntQualifSeq\']').val(parseInt(entQualifSeq) - 1)
                    $('input[id=\'EntQualifTypeCode\']').val(EntQualifData[parseInt(entQualifSeq) - 1].EntQualifTypeCode)
                    $('input[id=\'EntQualifTypeName\']').val(EntQualifData[parseInt(entQualifSeq) - 1].EntQualifTypeName)
                }
            } else {
                layer.msg('没有可查看的数据')
            }
        });

        /**编辑企业资质信息--右移**/
        $('#EnterpriseDownBtn').click(function () {
            let entQualifSeq = $('#EntQualifSeq').val()
            if (!entQualifSeq) {
                entQualifSeq = 0
            }
            if (EntQualifData.length > 0) {
                if (parseInt(entQualifSeq) < EntQualifData.length - 1) {
                    $('input[id=\'EntQualifSeq\']').val(parseInt(entQualifSeq) + 1)
                    $('input[id=\'EntQualifTypeCode\']').val(EntQualifData[parseInt(entQualifSeq) + 1].EntQualifTypeCode)
                    $('input[id=\'EntQualifTypeName\']').val(EntQualifData[parseInt(entQualifSeq) + 1].EntQualifTypeName)
                } else {
                    layer.msg('此为最后一条记录')
                }
            } else {
                layer.msg('没有可查看的数据')
            }
        });

        /**监听企业承诺**/
        form.on('checkbox(DeclaratioMaterialCode)', function (data) {
            if ($(data.elem).is(':checked')) {
                if (ieflag == 'I') {
                    DeclaratioMaterialCode = '101040'
                } else if (ieflag == 'E') {
                    DeclaratioMaterialCode = '102053'
                }
            }
        })

        // 启运日期
        laydate.render({elem: '#DespDate', theme: '#1E9FFF', fixed: true, format: 'yyyyMMdd'})

        /**编辑使用人信息**/
        let dec_users_index = null;
        $('body').on('click', '#DecUsersBtn', async function () {
            layer.open({
                type: 1,
                title: '编辑使用人信息',
                shadeClose: true,
                area: admin.screen() < 2 ? ['80%', '300px'] : ['910px', '530px'],
                content: $('#dec_users_template').html(),
            });
            $('#UseOrgPersonCode').focus();
            table.render({
                elem: '#dec_users_table'
                , toolbar: '#dec_users_tool'
                , defaultToolbar: ['filter']
                , colFilterRecord: 'local'
                , cols: [
                    [
                        {type: 'checkbox'}
                        , {field: 'index', title: '序号'}
                        , {field: 'UseOrgPersonCode', title: '使用单位联系人'}
                        , {field: 'UseOrgPersonTel', title: '使用单位联系电话'},
                    ]]
                , data: DecUsersData
                , limit: DecUsersData.length
                , height: 350,
            })
        });
        /**编辑使用人信息--点击行反填数据**/
        table.on('row(dec_users_table)', function (obj) {
            $('#UseOrgPersonCode').val(obj.data.UseOrgPersonCode);
            $('#UseOrgPersonTel').val(obj.data.UseOrgPersonTel);
            dec_users_index = obj.tr.data("index")
        });

        /**编辑使用人信息--保存**/
        form.on('submit(dec_users_submit_tem)', async (data) => {
            delete data.field.layTableCheckbox;
            if (dec_users_index != null) {
                DecUsersData.splice(dec_users_index, 1, data.field)
            } else {
                let UseOrgPersonTels = EntQualifData.map(item => item.UseOrgPersonTel);
                if ($.inArray(data.field.UseOrgPersonTel, UseOrgPersonTels) >= 0) {
                    return layer.msg('使用人已存在')
                }
                DecUsersData.push(data.field)
            }
            DecUsersData.forEach((value, index) => {
                value.index = index + 1
            })
            table.reload('dec_users_table', {
                data: DecUsersData,
                limit: DecUsersData.length,
            })
            $('#UseOrgPersonCode').val('')
            $('#UseOrgPersonTel').val('')
            $('#UseOrgPersonCode').focus()
            dec_users_index = null
        })
        /**编辑使用人信息--删除**/
        table.on('toolbar(dec_users_table)', function (obj) {
            let checkStatus = table.checkStatus(obj.config.id)
            let checkData = checkStatus.data
            switch (obj.event) {
                case 'add':
                    $('#UseOrgPersonCode').val('')
                    $('#UseOrgPersonTel').val('')
                    $('#UseOrgPersonCode').focus()
                    dec_users_index = null
                    break
                case 'delete':
                    if (checkData.length === 0) {
                        return layer.msg('请选择数据')
                    }
                    layer.confirm('真的删除么', {title: '提示'}, async (index) => {
                        let checkUseOrgPersonTels = checkData.map(item => item.UseOrgPersonTel);
                        let newDecUsersData = [];
                        DecUsersData.forEach(function (item, index) {
                            if ($.inArray(item.UseOrgPersonTel, checkUseOrgPersonTels) < 0) {
                                newDecUsersData.push(item)
                            }
                        });

                        table.reload('dec_users_table', {
                            data: newDecUsersData,
                            limit: newDecUsersData.length,
                        })
                        $('#UseOrgPersonCode').val('');
                        $('#UseOrgPersonTel').val('');
                        $('#UseOrgPersonCode').focus();
                        dec_users_index = null;
                        layer.close(index)
                    })
                    break
            }
        })

        /**编辑使用人信息--按enter保存**/
        $('body').on('keyup', '#UseOrgPersonTel', function (event) {
            if (event.keyCode == 13) {
                $('#dec_users_submit_tem').click();
                $('#UseOrgPersonCode').focus()
            }
        })

        /**特殊业务标识**/
        $('body').on('click', '#SpecDeclFlagOpen', function () {
            layer.open({
                type: 1,
                title: '特殊业务标识',
                shadeClose: true,
                area: admin.screen() < 2 ? ['80%', '300px'] : ['680px', '300px'],
                content: $('#spec_decl_flag_template').html(),
                success: function (layero, index) {
                    this.enterEsc = function (event) {
                        if (event.keyCode === 13) {
                            layer.closeAll()
                            return false
                        }
                    }
                    $(document).on('keydown', this.enterEsc)
                },
                end: function () {
                    if ($('#ContrItem').is(':disabled')) {
                        $('#CodeTS').focus()
                    } else {
                        $('#ContrItem').focus()
                    }
                    $(document).off('keydown', this.enterEsc)
                },
            })
            if (SpecDeclFlag.length > 0) {
                $('.tableDiv_spec_td').each(function (index, element) {
                    if (SpecDeclFlag[index] == '1') {
                        $(this).addClass('bgcolor')
                    }
                })
            }
        })

        /**特殊业务标识选择**/
        $('body').on('click', '.tableDiv_spec_td', function () {
            if ($(this).hasClass('bgcolor')) {
                $(this).removeClass('bgcolor')
            } else {
                $(this).addClass('bgcolor')
            }
            let data = $('#SpecDeclFlag').val().split(',')
            if (data.includes($(this).attr('name'))) {
                data.splice(data.indexOf($(this).attr('name')), 1)
            } else {
                let spec_data = []
                $('.tableDiv_spec_td').each(function () {
                    if ($(this).hasClass('bgcolor')) {
                        spec_data.push($(this).attr('name'))
                    }
                })
                data = spec_data
            }
            $('#SpecDeclFlag').val(data.join(','))
            SpecDeclFlag = []
            $('.tableDiv_spec_td').each(function () {
                if ($(this).hasClass('bgcolor')) {
                    SpecDeclFlag.push(1)
                } else {
                    SpecDeclFlag.push(0)
                }
            })
        })

        /**enter关联理由打开特殊业务标识**/
        $('body').on('keyup', '#CorrelationReasonFlagName', function (event) {
            if (event.keyCode == 13) {
                $('#SpecDeclFlagOpen').click()
            }
        })

        /**检验检疫签证申报要素**/
        $('body').on('click', '#DecRequestCertsBtn', async function () {
            layer.open({
                type: 1,
                title: '检验检疫签证申报要素',
                shadeClose: true,
                area: admin.screen() < 2 ? ['80%', '300px'] : ['1110px', '630px'],
                content: $('#dec_request_certs_template').html(),
            })
            let queryDocRep = [], check_data = []
            const data = layui.data('orderClearance').data[29]
            if (data) {
                for (let item of data) {
                    queryDocRep.push({
                        AppCertCode: item.CustomsCode,
                        ApplOri: 1,
                        ApplCopyQuan: 2,
                        AppCertName: item.Name,
                    })
                }
            }

            if (DecRequestCertsData.checkData) {
                check_data = DecRequestCertsData.checkData.map(function (item) {
                    return item.AppCertCode
                })
            }

            table.render({
                elem: '#dec_request_certs_table'
                , toolbar: true
                , defaultToolbar: ['filter']
                , colFilterRecord: 'local'
                , primaryKey: 'AppCertCode'
                , checkStatus: {
                    default: check_data,
                }
                , cols: [
                    [
                        {type: 'checkbox'}
                        , {type: 'numbers', title: '序号', width: 120}
                        , {field: 'AppCertCode', title: '证书代码', width: 240}
                        , {field: 'AppCertName', title: '证书名称', width: 300}
                        , {field: 'ApplOri', title: '正本数量', width: 240}
                        , {field: 'ApplCopyQuan', title: '副本数量', width: 240},
                    ]]
                , data: queryDocRep
                , limit: queryDocRep.length
                , height: 350,
            })

            laydate.render({elem: '#CmplDschrgDt', theme: '#1E9FFF', fixed: true})//卸毕日期

            $('#DomesticConsigneeEname').val(DecRequestCertsData.DomesticConsigneeEname)
            $('#OverseasConsignorCname').val(DecRequestCertsData.OverseasConsignorCname)
            $('#OverseasConsignorAddr').val(DecRequestCertsData.OverseasConsignorAddr)
            $('#CmplDschrgDt').val(DecRequestCertsData.CmplDschrgDt)
            $('#DeclGoodsEnames').val(DecRequestCertsData.DeclGoodsEnames)
        })

        /**保存检验检疫签证申报要素**/
        form.on('submit(dec_request_certs_submit)', function (data) {
            let checkData = table.checkStatus('dec_request_certs_table').data
            DecRequestCertsData = data.field;
            DecRequestCertsData.checkData = checkData;
            let arr = [];
            for (let item of DecRequestCertsData.checkData) {
                arr.push(item.AppCertName)
            }
            $('#DecRequestCerts').val(arr.join(','));
            layer.closeAll()
        })

        /**保存商品编号**/
        $('body').on('click', '#code_t_s_save', function () {
            const data = table.checkStatus('code_t_s_list_table').data;
            if (data.length == 0) {
                layer.msg('请选择商品');
                return
            }
            admin.DeclarationData = data[0].Declaration;
            $('#CodeTS').val(data[0].Code);
            $('#FirstUnit').val(data[0].Unit1);
            $('#FirstUnitName').val(data[0].Unit1Name);
            $('#SecondUnit').val(data[0].Unit2);
            $('#SecondUnitName').val(data[0].Unit2Name);
            layer.closeAll()
        })

        /**保存规格型号**/
        let declaration_edit = false;
        let declaration_index = null;
        form.on('submit(declaration_save)', function (data) {
            declaration_save_btn(data)
        })
        form.on('submit(declaration_next)', function (data) {
            declaration_save_btn(data)
            next_dec('edit')
        })
        form.on('submit(declaration_last)', function (data) {
            declaration_save_btn(data)
            last_dec('edit')
        })
        $('body').on('click', '#declaration_next_look', async function () {
            next_dec('look')
        })
        $('body').on('click', '#declaration_last_look', async function () {
            last_dec('look')
        })

        function submit_btn() {
            $('#declaration_last').attr('lay-submit', '')
            $('#declaration_next').attr('lay-submit', '')
            form.render()
        }

        function declaration_save_btn(data) {
            if (declaration_index != null && declaration_edit) {
                OrderItemsData[declaration_index].g_model = data.field.elements
                layer.msg('修改成功！')
                table.reload('order_pros', {
                    data: OrderItemsData,
                    limit: OrderItemsData.length,
                })
            } else {
                $('#GModel').val(data.field.elements)
                $('#GQty').focus()
                layer.closeAll()
            }
        }

        /**选择检验检疫名称**/
        $('body').on('click', '#ciq_name_open', async function () {
            if (!$('#CodeTS').val()) {
                layer.msg('请先填写商品编号')
                $('#CodeTS').focus()
                return
            }
            const hs = $('#CodeTS').val()
            const response = await admin.post(@{{ urlfor "CiqController.DataGrid" }}, JSON.stringify({
                NameLike: hs,
            }), true)
            const ciqs = response.rows
            layer.open({
                type: 1,
                title: '检验检疫编码列表',
                shadeClose: true,
                area: admin.screen() < 2 ? ['80%', '300px'] : ['910px', '450px'],
                content: $('#ciq_name_list').html(),
                success: function (layero, index) {
                    this.enterEsc = function (event) {
                        if (event.keyCode === 13) {
                            $('#ciq_name_save').click()
                            return false
                        }
                    }
                    $(document).on('keydown', this.enterEsc)
                },
                end: function () {
                    $('#GQty').focus()
                    $(document).off('keydown', this.enterEsc)
                },
            })

            table.render({
                elem: '#ciq_name_list_table'
                , toolbar: true
                , defaultToolbar: ['filter']
                , colFilterRecord: 'local'
                , primaryKey: 'Id'
                , checkStatus: {
                    default: [ciqs[0].Id],
                }
                , cols: [
                    [
                        {type: 'radio'}
                        , {field: 'Hs', title: 'HS代码', width: 150}
                        , {field: 'Name', title: '名称', width: 255}
                        , {field: 'CiqCode', title: 'CIQ代码', width: 120}
                        , {field: 'CiqName', title: 'CIQ代码中文名称'},
                    ]]
                , data: ciqs
                , limit: ciqs.length
                , height: 300,
            })
        })

        /**保存检验检疫名称**/
        $('body').on('click', '#ciq_name_save', function () {
            const data = table.checkStatus('ciq_name_list_table').data
            if (data.length == 0) {
                layer.msg('请选择编码')
                return
            }
            $('#CiqCode').val(data[0].CiqCode)
            $('#CiqName').val(data[0].Name)

            layer.closeAll()
        })

        /**编辑检验检疫货物规格**/
        $('body').on('click', '#goods_spec_open', async function () {
            layer.open({
                type: 1,
                title: '编辑检验检疫货物规格',
                shadeClose: true,
                area: admin.screen() < 2 ? ['80%', '300px'] : ['680px', '350px'],
                content: $('#goods_spec_list').html(),
            })
            $('#Stuff').focus()
            laydate.render({elem: '#ProdValidDt', theme: '#1E9FFF', fixed: true})
            laydate.render({elem: '#ProduceDate', theme: '#1E9FFF', fixed: true})

            $(`#Stuff`).val(OrderItemStuff)
            $(`#ProdValidDt`).val(OrderItemProdValidDt)
            $(`#ProdQgp`).val(OrderItemProdQgp)
            $(`#EngManEntCnm`).val(OrderItemEngManEntCnm)
            $(`#GoodsSpec`).val(OrderItemGoodsSpec)
            $(`#GoodsModel`).val(OrderItemGoodsModel)
            $(`#GoodsBrand`).val(OrderItemGoodsBrand)
            $(`#ProduceDate`).val(OrderItemProduceDate)
            $(`#ProdBatchNo`).val(OrderItemProdBatchNo)
        })

        /**保存检验检疫货物规格**/
        form.on('submit(goods_spec_save)', function (data) {
            let GoodsSpecData = ''
            for (let item in data.field) {
                let e = [
                    'Stuff',
                    'ProdValidDt',
                    'ProdQgp',
                    'EngManEntCnm',
                    'GoodsSpec',
                    'GoodsModel',
                    'GoodsBrand',
                    'ProduceDate',
                    'ProdBatchNo']
                if ($.inArray(item, e) >= 0 && data.field[item]) {
                    GoodsSpecData += data.field[item] + ';'
                }
            }
            OrderItemStuff = $(`#Stuff`).val()
            OrderItemProdValidDt = $(`#ProdValidDt`).val()
            OrderItemProdQgp = $(`#ProdQgp`).val()
            OrderItemEngManEntCnm = $(`#EngManEntCnm`).val()
            OrderItemGoodsSpec = $(`#GoodsSpec`).val()
            OrderItemGoodsModel = $(`#GoodsModel`).val()
            OrderItemGoodsBrand = $(`#GoodsBrand`).val()
            OrderItemProduceDate = $(`#ProduceDate`).val()
            OrderItemProdBatchNo = $(`#ProdBatchNo`).val()
            layer.closeAll()
            $('#goods_attr_open').click()
        })

        /**编辑产品许可证/审批/备案信息**/
        $('body').on('click', '#goodsTargetBtn', async function () {
            if (!($('#CodeTS').val())) {
                layer.msg('请填写商品编号')
                $('#CodeTS').focus()
                return
            }
            layer.open({
                type: 1,
                title: '编辑编辑产品许可证/审批/备案信息',
                shadeClose: true,
                area: admin.screen() < 2 ? ['80%', '300px'] : ['910px', '530px'],
                content: $('#dec_goods_template').html(),
            })
            $('#OrderItemLimitOId').val($('#OrderItemId').val())
            $('#LicenceCodeTs').val($('#CodeTS').val())
            $('#LicenceGName').val($('#GName').val())
            $('#LicenceCiqName').val($('#CiqName').val())
            table.render({
                elem: '#dec_goods_table'
                , toolbar: '#dec_goods_tool'
                , defaultToolbar: ['filter']
                , colFilterRecord: 'local'
                , cols: [
                    [
                        {type: 'checkbox'}
                        , {field: 'GoodsNo', title: '序号', width: 80}
                        , {field: 'LicTypeCode', title: '许可证类别代码', width: 150}
                        , {field: 'LicTypeName', title: '证书类别名称', width: 150}
                        , {field: 'LicenceNo', title: '许可证编码', width: 130}
                        , {field: 'LicWrtofDetailNo', title: '核销货物序号', width: 150}
                        , {field: 'LicWrtofQty', title: '核销数量', width: 110}
                        , {field: 'LicWrtofQtyUnitName', title: '核销数量单位', width: 140},
                    ]]
                , data: OrderItemLimits
                , limit: OrderItemLimits.length
                , height: 350,
            })

            $('#LicTypeName').focus()
            /**自动完成--许可证类别**/
            let site_code = {
                dataType: 'orderClearance',
                type: 13,
                name: '企业产品许可类别代码',
                filter_type: 's',
                id: ['#LicTypeName'],
                after: ['#LicTypeCode'],
            }
            await admin.base_clearance_data_auto(site_code)
            /**自动完成--核销数量单位**/
            let unit_measurement = {
                dataType: 'commonClearance',
                type: 23,
                name: '计量单位代码',
                filter_type: 's',
                id: ['#LicWrtofQtyUnitName'],
                after: ['#LicWrtofQtyUnit'],
            }
            await admin.base_clearance_data_auto(unit_measurement)

        })

        /**编辑产品许可证/审批/备案信息--点击行反填数据**/
        let orderItemLimitIndex = 0
        table.on('row(dec_goods_table)', function (obj) {
            orderItemLimitIndex = obj.tr.data("index")
            $('#OrderItemLimitId').val(obj.data.Id)
            $('#LimitGoodsNo').val(obj.data.GoodsNo)
            $('#LicTypeCode').val(obj.data.LicTypeCode)
            $('#LicTypeName').val(obj.data.LicTypeName)
            $('#LicenceNo').val(obj.data.LicenceNo)
            $('#LicWrtofDetailNo').val(obj.data.LicWrtofDetailNo)
            $('#LicWrtofQty').val(obj.data.LicWrtofQty)
            $('#LicWrtofQtyUnit').val(obj.data.LicWrtofQtyUnit)
            $('#LicWrtofQtyUnitName').val(obj.data.LicWrtofQtyUnitName)
            $('#LicTypeName').focus()
        })

        let order_item_limit_table_names = [
            'OrderItemLimitId',
            'LimitGoodsNo',
            'LicTypeCode',
            'LicTypeName',
            'LicenceNo',
            'LicWrtofDetailNo',
            'LicWrtofQty',
            'LicWrtofQtyUnit',
            'LicWrtofQtyUnitName',
        ]

        let order_item_limit_set_empty = {
            table_name: 'dec_goods_table',
            table_datas: OrderItemLimits,
            from_input_names: order_item_limit_table_names,
            focus_input_name: 'LicTypeName',
        };

        /**编辑产品许可证/审批/备案信息--保存**/
        form.on('submit(dec_goods_submit)', async (data) => {
            delete data.field.layTableCheckbox;
            let orderItemLimitId = data.field.OrderItemLimitId;
            if (orderItemLimitId && orderItemLimitId != 0) {
                let result = await admin.patch(`/order_item_limit/update/${orderItemLimitId}`, data.field);
                if (result.status) {
                    OrderItemLimits.splice(orderItemLimitIndex, 1, result.obj)
                }
            } else {
                data.field.GoodsNo = OrderItemLimits.length + 1;
                let result = await admin.post('/order_item_limit/store', data.field);
                if (result.status) {
                    OrderItemLimits.push(result.obj)
                }
            }
            order_item_limit_set_empty.table_datas = OrderItemLimits;
            admin.SetEmptyData(order_item_limit_set_empty)
        })

        /**编辑产品许可证/审批/备案信息--删除**/
        table.on('toolbar(dec_goods_table)', function (obj) {
            let checkStatus = table.checkStatus(obj.config.id)
            let checkData = checkStatus.data
            switch (obj.event) {
                case 'add':
                    order_item_limit_set_empty.table_datas = OrderItemLimits
                    admin.SetEmptyData(order_item_limit_set_empty)
                    orderItemLimitIndex = 0
                    break
                case 'delete':
                    if (checkData.length === 0) {
                        return layer.msg('请选择数据')
                    }

                    layer.confirm('真的删除么', {title: '提示'}, async (index) => {
                        let delData = admin.getDelIds(OrderItemLimits, checkData);
                        delData.Datas.forEach(function (item, index, arr) {
                            item.GoodsNo = `${index + 1}`;
                            item.LicWrtofQty = parseInt(item.LicWrtofQty);
                            item.OrderItemId = parseInt(item.OrderItemId);
                            item.Id = parseInt(item.Id)
                        });

                        let result = await admin.post(`/order_item_limit/delete/`, JSON.stringify({
                            Limits: delData.Datas,
                            Ids: delData.Ids,
                        }));

                        if (result.status) {
                            order_item_limit_set_empty.table_datas = delData.Datas;
                            admin.SetEmptyData(order_item_limit_set_empty)
                        }
                        layer.close(index)
                    })
                    break
            }
        })

        /**编辑产品许可证/审批/备案信息--按enter保存**/
        $('body').on('keyup', '#lic_wrtof_qty_unit_name', function (event) {
            if (event.keyCode == 13) {
                $('#dec_goods_submit').click()
                $('#LicTypeName').focus()
            }
            q
        })

        /**许可证VIN信息**/
        let OrderItemLimitVinDatas = []
        form.on('submit(dec_goods_vin)', async (data) => {
            layer.open({
                type: 1,
                title: '编辑许可证VIN',
                shadeClose: true,
                area: admin.screen() < 2 ? ['80%', '300px'] : ['1002px', '590px'],
                content: $('#dec_goods_vin_template').html(),
            })

            OrderItemLimitVinDatas = OrderItemLimits[orderItemLimitIndex].OrderItemLimitVins || []
            table.render({
                elem: '#dec_goods_vin_table'
                , toolbar: '#dec_goods_vin_tool'
                , defaultToolbar: ['filter']
                , colFilterRecord: 'local'
                , cols: [
                    [
                        {type: 'checkbox'}
                        , {type: 'numbers', title: '序号', width: 100}
                        , {field: 'VinNo', title: 'VIN序号', width: 100}
                        , {field: 'BillLadDate', title: '提/运单日期', width: 140}
                        , {field: 'QualityQgp', title: '质量保质期', width: 130}
                        , {field: 'MotorNo', title: '发动机号或电机号', width: 200}
                        , {field: 'VinCode', title: '车辆识别代码(VIN)', width: 200}
                        , {field: 'ChassisNo', title: '底盘(车架)号', width: 200}
                        , {field: 'InvoiceNo', title: '发票号', width: 130}
                        , {field: 'InvoiceNum', title: '发票所列数量', width: 150}
                        , {field: 'ProdCnnm', title: '品名(中文名称)', width: 220}
                        , {field: 'ProdEnnm', title: '品名(英文名称)', width: 220}
                        , {field: 'ModelEn', title: '型号(英文名称)', width: 220}
                        , {field: 'PricePerUnit', title: '单价', width: 120},
                    ]]
                , data: OrderItemLimitVinDatas
                , limit: OrderItemLimitVinDatas.length
                , height: 350,
            })

            laydate.render({elem: '#BillLadDate', theme: '#1E9FFF', fixed: true})

            $('#LicTypeCodeVinName').val(OrderItemLimits[orderItemLimitIndex].LicTypeName)
            $('#VinLicenceNo').val(OrderItemLimits[orderItemLimitIndex].LicenceNo)
            $('#OrderItemLimitVinOId').val(OrderItemLimits[orderItemLimitIndex].Id)
            $('#VinNo').focus()
        })

        /**许可证VIN信息--点击行反填数据**/
        let orderItemLimitVinIndex = null
        table.on('row(dec_goods_vin_table)', function (obj) {
            orderItemLimitVinIndex = obj.tr.data("index")
            $('#OrderItemLimitVinId').val(obj.data.Id)
            $('#GoodsLimitVinSeqNo').val(orderItemLimitVinIndex + 1)
            $('#VinNo').val(obj.data.VinNo)
            $('#BillLadDate').val(obj.data.BillLadDate)
            $('#QualityQgp').val(obj.data.QualityQgp)
            $('#MotorNo').val(obj.data.MotorNo)
            $('#VinCode').val(obj.data.VinCode)
            $('#ChassisNo').val(obj.data.ChassisNo)
            $('#InvoiceNo').val(obj.data.InvoiceNo)
            $('#InvoiceNum').val(obj.data.InvoiceNum)
            $('#ProdCnnm').val(obj.data.ProdCnnm)
            $('#ProdEnnm').val(obj.data.ProdEnnm)
            $('#ModelEn').val(obj.data.ModelEn)
            $('#PricePerUnit').val(obj.data.PricePerUnit)
            $('#VinNo').focus()
        })

        let order_item_limit_vin_table_names = [
            'OrderItemLimitVinId',
            'VinNo',
            'VinNo',
            'BillLadDate',
            'QualityQgp',
            'MotorNo',
            'VinCode',
            'ChassisNo',
            'InvoiceNo',
            'InvoiceNum',
            'ProdCnnm',
            'ProdEnnm',
            'ModelEn',
            'PricePerUnit',
        ]
        let order_item_limit_vin_set_empty = {
            table_name: 'dec_goods_vin_table',
            table_datas: OrderItemLimitVinDatas,
            from_input_names: order_item_limit_vin_table_names,
            focus_input_name: 'VinNo',
        }

        /**许可证VIN信息--保存**/
        form.on('submit(dec_goods_vin_submit)', async (data) => {
            delete data.field.layTableCheckbox
            let orderItemLimitVinId = data.field.OrderItemLimitVinId;
            if (orderItemLimitVinId && orderItemLimitVinId != 0) {
                let result = await admin.patch(`/order_item_limit_vin/update/${orderItemLimitVinId}`, data.field);
                if (result.status) {
                    OrderItemLimitVinDatas.splice(orderItemLimitVinIndex, 1, result.obj)
                }
            } else {
                let result = await admin.post('/order_item_limit_vin/store', data.field);
                if (result.status) {
                    OrderItemLimitVinDatas.push(result.obj)
                }
            }

            order_item_limit_vin_set_empty.table_datas = OrderItemLimitVinDatas
            admin.SetEmptyData(order_item_limit_vin_set_empty)
        })

        /**许可证VIN信息--删除**/
        table.on('toolbar(dec_goods_vin_table)', function (obj) {
            let checkStatus = table.checkStatus(obj.config.id)
            let checkData = checkStatus.data
            switch (obj.event) {
                case 'add':
                    order_item_limit_vin_set_empty.table_datas = OrderItemLimitVinDatas
                    admin.SetEmptyData(order_item_limit_set_empty)
                    orderItemLimitVinIndex = null
                    break
                case 'delete':
                    if (checkData.length === 0) {
                        return layer.msg('请选择数据')
                    }
                    layer.confirm('真的删除么', {title: '提示'}, async (index) => {
                        let delData = admin.getDelIds(OrderItemLimitVinDatas, checkData);
                        delData.Datas.forEach(function (item, index, arr) {
                            item.OrderItemVinId = parseInt(item.OrderItemVinId);
                            item.Id = parseInt(item.Id)
                        });

                        let result = await admin.post(`/order_item_limit_vin/delete/`, JSON.stringify({
                            Ids: delData.Ids,
                        }));

                        if (result.status) {
                            order_item_limit_vin_set_empty.table_datas = delData.Datas;
                            admin.SetEmptyData(order_item_limit_set_empty)
                        }

                        layer.close(index)
                    })

                    break
            }
        })

        /**许可证VIN信息--按enter保存**/
        $('body').on('keyup', '#PricePerUnit', function (event) {
            if (event.keyCode == 13) {
                $('#dec_goods_vin_submit').click()
                $('#VinNo').focus()
            }
        })

        /**货物属性**/
        $('body').on('click', '#goods_attr_open', async function () {
            const data = layui.data('orderClearance').data[22]
            const len = data.length
            let result = []
            const sliceNum = 4
            for (let i = 0; i < len / sliceNum; i++) {
                result.push(data.slice(i * sliceNum, (i + 1) * sliceNum))
            }
            laytpl($('#goods_attr_data_template').html()).render(result, function (html) {
                $('#goods_attr_data_list').html(html)
            })
            layer.open({
                type: 1,
                title: '货物属性',
                shadeClose: true,
                area: admin.screen() < 2 ? ['80%', '300px'] : ['680px', '300px'],
                content: $('#goods_attr_data_list').html(),
                success: function (layero, index) {
                    this.enterEsc = function (event) {
                        if (event.keyCode === 13) {
                            layer.closeAll()
                            return false
                        }
                    }
                    $(document).on('keydown', this.enterEsc)
                },
                end: function () {
                    $(document).off('keydown', this.enterEsc)
                    $('#PurposeName').focus()
                },
            })
            $('.tableDiv_attr_td').each(function () {
                const result = OrderItemGoodsAttr.some(item => {
                    if (item == $(this).data('id')) {
                        return true
                    }
                })
                if (result) {
                    $(this).addClass('bgcolor')
                }
            })
        })

        /**货物属性选择**/
        $('body').on('click', '.tableDiv_attr_td', function () {
            if ($(this).hasClass('bgcolor')) {
                $(this).removeClass('bgcolor')
            } else {
                $(this).addClass('bgcolor')
            }
            OrderItemGoodsAttr.push($(this).data('id'))
            OrderItemGoodsAttrName.push($(this).attr('name'))
            $('#GoodsAttr').val(OrderItemGoodsAttrName)

        })

        /**编辑货物危险信息**/
        $('body').on('click', '#dangerBtn', async function () {
            layer.open({
                type: 1,
                title: '编辑货物危险信息',
                shadeClose: true,
                area: admin.screen() < 2 ? ['80%', '300px'] : ['680px', '270px'],
                content: $('#dang_list').html(),
            })
            $('#NoDangFlagName').focus()

            let dange_good = {
                dataType: 'orderClearance',
                type: 20,
                name: '危包规格代码',
                filter_type: 's',
                id: ['#DangPackSpecName'],
                after: ['#DangPackSpec'],
            }
            await admin.base_clearance_data_auto(dange_good)

            let dang_pack_typ = {
                dataType: 'orderClearance',
                type: 43,
                name: '危包类别',
                filter_type: 's',
                id: ['#DangPackTypeName'],
                after: ['#DangPackType'],
            }
            await admin.base_clearance_data_auto(dang_pack_typ)

            // 非危险化学品
            let lcl_flag = {
                dataType: 'orderClearance',
                type: 42,
                name: '拼箱规格',
                filter_type: 's',
                id: ['#NoDangFlagName'],
                after: ['#NoDangFlag'],
            }
            await admin.base_clearance_data_auto(lcl_flag)

            $('#NoDangFlag').val(OrderItemNoDangFlag)
            $('#NoDangFlagName').val(OrderItemNoDangFlagName)
            $('#DangName').val(OrderItemDangName)
            $('#UnCode').val(OrderItemUnCode)
            $('#DangPackType').val(OrderItemDangPackType)
            $('#DangPackTypeName').val(OrderItemDangPackTypeName)
            $('#DangPackSpec').val(OrderItemDangPackSpec)
            $('#DangPackSpecName').val(OrderItemDangPackSpecName)

        })

        /**保存货物危险信息**/
        form.on('submit(dang_save)', function (data) {
            OrderItemNoDangFlag = $('#NoDangFlag').val()
            OrderItemNoDangFlagName = $('#NoDangFlagName').val()
            OrderItemDangName = $('#DangName').val()
            OrderItemUnCode = $('#UnCode').val()
            OrderItemDangPackType = $('#DangPackType').val()
            OrderItemDangPackTypeName = $('#DangPackTypeName').val()
            OrderItemDangPackSpec = $('#DangPackSpec').val()
            OrderItemDangPackSpecName = $('#DangPackSpecName').val()

            layer.closeAll()
        })

        /**调用历史申报数据**/
        $('body').on('click', '#his_dec', async function () {
            his_dec_index = layer.open({
                type: 1,
                title: `历史申报数据${$('#CodeTS').val()}-${$('#GName').val()}`,
                shadeClose: true,
                area: admin.screen() < 2 ? ['80%', '300px'] : ['910px', '730px'],
                content: $('#elements_his_list').html(),
                success: function (layero, index) {
                    this.enterEsc = function (event) {
                        if (event.keyCode === 13) {
                            $('#elements_his_save').click()
                            return false
                        }
                    }
                    $(document).on('keydown', this.enterEsc)
                },
                end: function () {
                    $('#val0Name').focus()
                    $(document).off('keydown', this.enterEsc)
                },
            })
            let url
            if ($('#ManualNo').val()) {
                url = `/order/history_good_g_model?search=manual_no:${$('#ManualNo').val()};trade_code:${$('#TradeCode').val()};code_t_s:${$('#code_t_s').val()};IEFlag:` + ieflag
            } else {
                url = `/order/history_good_g_model?search=trade_code:${$('#TradeCode').val()};code_t_s:${$('#CodeTS').val()};IEFlag:` + ieflag
            }
            admin.elements_his_data = await admin.get(url)
            table.render({
                elem: '#elements_his_list_table'
                , toolbar: true
                , defaultToolbar: ['filter']
                , colFilterRecord: 'local'
                , cols: [
                    [
                        {type: 'radio'}
                        , {
                        field: 'apl_date', title: '申报日期', width: 160, templet: function (data) {
                            return data.order.apl_date
                        },
                    }
                        , {field: 'g_model', title: '申报要素'},
                    ]]
                , data: admin.elements_his_data
                , limit: 10
                , page: true
                , height: 550,
            })
            $('.layui-table-view[lay-id=\'elements_his_list_table\'] .layui-table-body tr[data-index=\'0\'] .layui-form-radio').click()
        })
        /**搜索历史申报要素**/
        $('body').on('input', '#elements_his_search', async function () {
            const text = $(this).val()
            const filter_data = admin.elements_his_data.filter(item => {
                return (item.g_model).indexOf(text) > -1
            })
            table.reload('elements_his_list_table', {
                data: filter_data,
            })
            $('.layui-table-view[lay-id=\'elements_his_list_table\'] .layui-table-body tr[data-index=\'0\'] .layui-form-radio').click()
        })
        /**保存历史申报要素**/
        $('body').on('click', '#elements_his_save', function () {
            const data = table.checkStatus('elements_his_list_table').data
            $('#elements').val(data[0].g_model)
            const arrAnge = data[0].g_model.split('|')
            arrAnge.forEach((value, index) => {
                $(`#val${index}`).val(value)
            })
            admin.brand_type_data.forEach((value, index) => {
                if (value.id == $('#val0').val()) {
                    $('#val0Name').val(value.value)
                }
            })
            admin.export_benefits_data.forEach((value, index) => {
                if (value.id == $('#val1').val()) {
                    $('#val1Name').val(value.value)
                }
            })
            layer.close(his_dec_index)
        })

        /**征免方式回车保存商品**/
        $('body').on('keyup', '#duty_mode_name', function (event) {
            edit_row = $('#g_no').val()
            const eCode = event.keyCode ? event.keyCode : event.which ? event.which : event.charCode
            if (event.shiftKey != 1 && eCode == 13) {
                if ($('#decListShow').attr('isdeclistshow') == 0) {
                    $('#order_pros_submit').click()
                } else {
                    $('#goods_spec_open').click()
                }
            }
            $('.layui-table-main').scrollTop(38 * (edit_row - 1))
        })

        /**用途回车保存商品**/
        $('body').on('keyup', '#purpose_name', function (event) {
            edit_row = $('#g_no').val()
            const eCode = event.keyCode ? event.keyCode : event.which ? event.which : event.charCode
            if (event.shiftKey != 1 && eCode == 13) {
                $('#order_pros_submit').click()
            }
            $('.layui-table-main').scrollTop(38 * (edit_row - 1))
        });

        /**保存商品**/
        form.on('submit(order_pros_submit)', async function (data) {
            if ($('#GNo').val() > 50) {
                layer.msg('商品数量不能超过50条！');
                return
            }
            if (OrderItemsData.length >= 51) {
                layer.msg('商品数量不能超过50条！');
                return
            }
            if (OrderItemsData.length > 1) {
                if (data.field.TradeCurr != OrderItemsData[0].TradeCurr) {
                    return layer.msg('币制不一致！')
                }
            }
            if (data.field.GUnit == data.field.FirstUnit) {
                if (data.field.GQty != data.field.FirstQty) {
                    return layer.msg('成交数量与法定第一数量不一致！')
                }
            }
            if (data.field.GUnit == data.field.SecondUnit) {
                if (data.field.GQty != data.field.SecondQty) {
                    return layer.msg('成交数量与法定第二数量不一致！')
                }
            }
            if (data.field.CodeTS.toString().length != 10) {
                return layer.msg('商品编号必须为10位！')
            }
            data.field.DeclPrice = admin.formatnumber(data.field.DeclPrice, 4);
            data.field.DeclTotal = admin.formatnumber(data.field.DeclTotal, 4);

            // 检验检疫货物规格
            data.field.Stuff = OrderItemStuff;
            data.field.ProdValidDt = OrderItemProdValidDt;
            data.field.ProdQgp = OrderItemProdQgp;
            data.field.EngManEntCnm = OrderItemEngManEntCnm;
            data.field.GoodsSpec = OrderItemGoodsSpec;
            data.field.GoodsModel = OrderItemGoodsModel;
            data.field.GoodsBrand = OrderItemGoodsBrand;
            data.field.ProduceDate = OrderItemProduceDate;
            data.field.ProdBatchNo = OrderItemProdBatchNo;

            // 货物属性
            data.field.GoodsAttr = JSON.stringify(OrderItemGoodsAttr);
            data.field.GoodsAttrName = JSON.stringify(OrderItemGoodsAttrName);

            // 危险货物信息
            data.field.Stuff = OrderItemNoDangFlag;
            data.field.NoDangFlagName = OrderItemNoDangFlagName;
            data.field.DangName = OrderItemDangName;
            data.field.UnCode = OrderItemUnCode;
            data.field.DangPackType = OrderItemDangPackType;
            data.field.DangPackTypeName = OrderItemDangPackTypeName;
            data.field.DangPackSpec = OrderItemDangPackSpec;
            data.field.DangPackSpecName = OrderItemDangPackSpecName;
            data.field.OrderItemLimits = OrderItemLimits;// 产品资质

            data.field.OrderId = order_id;  // id
            if (isOrderItemInsert) { //插入
                OrderItemsData.splice(orderItemIndex - 1, 0, data.field);  // id
                OrderItemsData.forEach((value, index) => {
                    value.GNo = index + 1
                });

                await admin.patch(`/order_item/updateMul/`, JSON.stringify({
                    OrderItems: OrderItemsData,
                }));

            } else {
                let orderItemId = data.field.OrderItemId;
                if (orderItemId && orderItemId != '0') {
                    let result = await admin.patch(`/order_item/update/${orderItemId}`, data.field);
                    if (result.status) {
                        OrderItemsData.splice(orderItemIndex, 1, result.obj)
                    }
                } else {
                    let result = await admin.post('/order_item/store', data.field);
                    if (result.status) {
                        OrderItemsData.push(result.obj)
                    }
                }
            }

            setOrderItemEmptyData(false)
        });

        /**商品--点击行反填数据**/
        table.on('row(order_pros)', function (obj) {
            orderItemIndex = obj.tr.data("index");
            let GoodsSpecData = '';
            let e = [
                'Stuff',
                'ProdValidDt',
                'ProdQgp',
                'EngManEntCnm',
                'GoodsSpec',
                'GoodsModel',
                'GoodsBrand',
                'ProduceDate',
                'ProdBatchNo',
            ];
            for (let item in obj.data) {
                if (item == 'Id') {
                    $(`#OrderItemId`).val(obj.data[item])
                } else if (item == 'GoodsAttrName' && obj.data[item]) {
                    OrderItemGoodsAttrName = JSON.parse(obj.data[item])
                } else if (item == 'GoodsAttr' && obj.data[item]) {
                    OrderItemGoodsAttr = JSON.parse(obj.data[item])
                } else if (item == 'NoDangFlag') {
                    OrderItemNoDangFlag = obj.data[item]
                } else if (item == 'NoDangFlagName') {
                    OrderItemNoDangFlagName = obj.data[item]
                } else if (item == 'DangName') {
                    OrderItemDangName = obj.data[item]
                } else if (item == 'UnCode') {
                    OrderItemUnCode = obj.data[item]
                } else if (item == 'DangPackType') {
                    OrderItemDangPackType = obj.data[item]
                } else if (item == 'DangPackTypeName') {
                    OrderItemDangPackTypeName = obj.data[item]
                } else if (item == 'DangPackSpec') {
                    OrderItemDangPackSpec = obj.data[item]
                } else if (item == 'DangPackSpecName') {
                    OrderItemDangPackSpecName = obj.data[item]
                } else if ($.inArray(item, e) >= 0 && obj.data[item]) {
                    GoodsSpecData += obj.data[item] + ';';
                    if (item == 'Stuff') {
                        OrderItemStuff = obj.data[item]
                    } else if (item == 'ProdValidDt') {
                        OrderItemProdValidDt = obj.data[item]
                    } else if (item == 'ProdQgp') {
                        OrderItemProdQgp = obj.data[item]
                    } else if (item == 'EngManEntCnm') {
                        OrderItemEngManEntCnm = obj.data[item]
                    } else if (item == 'GoodsSpec') {
                        OrderItemGoodsSpec = obj.data[item]
                    } else if (item == 'GoodsModel') {
                        OrderItemGoodsModel = obj.data[item]
                    } else if (item == 'GoodsBrand') {
                        OrderItemGoodsBrand = obj.data[item]
                    } else if (item == 'ProduceDate') {
                        OrderItemProduceDate = obj.data[item]
                    } else if (item == 'ProdBatchNo') {
                        OrderItemProdBatchNo = obj.data[item]
                    }
                } else {
                    $(`#${item}`).val(obj.data[item])
                }
            }
            OrderItemLimits = obj.data.OrderItemLimits; // 产品资质
            $('#GoodsAttr').val(OrderItemGoodsAttrName); // 货物属性
            $('#GoodsSpecData').val(GoodsSpecData); // 检验检疫货物规格

            declaration_index = orderItemIndex - 1;
            // $('#order_pros_form input').removeClass('is_check_fail');
            //if (statusString == '复核不通过') {
            // if (order_i_edit_data.reject_logs.length > 0) {
            //   if (order_i_edit_data.reject_logs[order_i_edit_data.reject_logs.length - 1].recheck_error_input_ids) {
            //     for (let item of order_i_edit_data.reject_logs[order_i_edit_data.reject_logs.length -
            //     1].recheck_error_input_ids) {
            //       if (item.index == order_pros_index) {
            //         for (let id of item.id) {
            //           $(`#${id}`).addClass('is_check_fail')
            //         }
            //       }
            //     }
            //   }
            // }
            // }
        });

        /**商品列表--按钮操作**/
        table.on('toolbar(order_pros)', async function (obj) {
            let checkStatus = table.checkStatus(obj.config.id);
            let checkData = checkStatus.data;
            switch (obj.event) {
                case 'add':
                    setOrderItemEmptyData(false);
                    break;
                case 'delete':
                    if (checkData.length === 0) {
                        return layer.msg('请选择数据')
                    }
                    layer.confirm('真的删除么', {title: '提示'}, async (index) => {
                        let delData = admin.getDelIds(OrderItemsData, checkData);
                        OrderItemsData = delData.Datas;
                        OrderItemsData.forEach(function (item, index, arr) {
                            item.OrderId = parseInt(item.OrderId);
                            item.GNo = index + 1;
                            item.Id = parseInt(item.Id)
                        });

                        let result = await admin.post(`/order_item/delete/`, JSON.stringify({
                            Limits: OrderItemsData,
                            Ids: delData.Ids,
                        }));

                        if (result.status) {
                            setOrderItemEmptyData(false)
                        }

                        layer.close(index)
                    });
                    break;
                case 'copy':
                    if (checkData.length === 0) {
                        return layer.msg('请选择数据')
                    }
                    if (checkData.length != 1) {
                        return layer.msg('只能选择一条数据复制')
                    }
                    if (OrderItemsData.length >= 50) {
                        return layer.msg('商品数量不能超过50条！')
                    }

                    let resultCopy = await admin.post('/order_item/copy/' + checkData[0].Id, {GNo: OrderItemsData.length + 1});
                    if (resultCopy.status) {
                        OrderItemsData.push(resultCopy.obj);
                        setOrderItemEmptyData(false)
                    }
                    break;
                case 'up':
                    if (checkData.length === 0) {
                        return layer.msg('请选择数据')
                    }
                    if (checkData.length != 1) {
                        return layer.msg('只能选择一条数据移动')
                    }
                    if (checkData[0].GNo == 1) {
                        return layer.msg('已是第一条商品表体，无法执行上移操作。')
                    }

                    const upIndex = parseInt(checkData[0].GNo) - 1;
                    OrderItemsData = admin.swapItems(OrderItemsData, upIndex, upIndex - 1);
                    OrderItemsData.forEach((value, index) => {
                        value.GNo = index + 1
                    });

                    let responseUp = await admin.patch(`/order_item/updateMul/`, JSON.stringify({
                        OrderItems: OrderItemsData,
                    }));

                    if (responseUp.status) {
                        setOrderItemEmptyData(false)
                    }
                    break;
                case 'down':
                    if (checkData.length === 0) {
                        return layer.msg('请选择数据')
                    }
                    if (checkData.length != 1) {
                        return layer.msg('只能选择一条数据移动')
                    }
                    if (checkData[0].GNo == OrderItemsData.length) {
                        return layer.msg('已是最后一条数据，无法执行下移移操作。')
                    }
                    const downIndex = parseInt(checkData[0].GNo) - 1;
                    OrderItemsData = admin.swapItems(OrderItemsData, downIndex, downIndex + 1);
                    OrderItemsData.forEach((value, index) => {
                        value.GNo = index + 1
                    });

                    let responseDown = await admin.patch(`/order_item/updateMul/`, JSON.stringify({
                        OrderItems: OrderItemsData,
                    }));

                    if (responseDown.status) {
                        setOrderItemEmptyData(false)
                    }
                    break;
                case 'insert':
                    if (checkData.length === 0) {
                        return layer.msg('请选择数据')
                    }
                    if (checkData.length != 1) {
                        return layer.msg('只能选择一条数据插入')
                    }
                    setOrderItemEmptyData(false)
                    $('#GNo').val(checkData[0].GNo + 1);
                    isOrderItemInsert = true;
                    break;
                case 'again':
                    if (!($('#CodeTS').val().trim())) {
                        return layer.msg('请先填写商品编码')
                    }
                    const hs_code_data = await admin.get(`/hs_code/get_hs_code_by_code/${OrderItemsData[declaration_index].CodeTS}`);
                    if (hs_code_data.length === 0) {
                        return layer.msg('此商品没有申报要素')
                    }

                    declaration_edit = true;
                    const declaration_data_array = hs_code_data[0].Declaration.split(';');
                    const data = declaration_data_array.map((item, index) => {
                        if (index < 9) {
                            return item.substr(1)
                        } else {
                            return item.substr(2)
                        }
                    });

                    data.type = 'again';
                    laytpl($('#declaration_template').html()).render(data, function (html) {
                        $('#declaration_list').html(html)
                    })

                    layer.open({
                        type: 1,
                        title: '商品规范申报-商品申报要素',
                        shadeClose: true,
                        area: admin.screen() < 2 ? ['80%', '300px'] : ['1180px', '600px'],
                        content: `<div id="declaration_list_reload">${$('#declaration_list').html()}</div>`,
                        end: function () {
                            $(`.layui-table-view[lay-id='order_pros'] .layui-table-body tr input`).each(function (index, el) {
                                el.checked = false
                            })
                            form.render('checkbox')
                            $(`.layui-table-view[lay-id='order_pros'] .layui-table-body tr[data-index=${declaration_index}]`).click()
                            $('#GQty').focus()
                            declaration_edit = false
                            $(`.layui-table-view[lay-id='order_pros'] .layui-table-body`).animate({
                                scrollTop: $(
                                    `.layui-table-view[lay-id='order_pros'] .layui-table-body tr[data-index=${declaration_index}]`)[0].offsetTop,
                            }, 0)
                        },
                    })
                    $('.manual_no_btn_next').show()
                    $('body #val0Name').focus()
                    $('#selectCodeTs').val(OrderItemsData[declaration_index].GName);
                    $('#good_information').val(`${OrderItemsData[declaration_index].GNo}-${OrderItemsData[declaration_index].ContrItem
                        ? OrderItemsData[declaration_index].ContrItem
                        : '一般贸易'}-${OrderItemsData[declaration_index].GName}`);
                    let brand_type = layui.data('orderClearance').data[30];
                    let data_filter = [];
                    for (let item of brand_type) {
                        data_filter.push({
                            id: item.CustomsCode,
                            label: `${item.CustomsCode}-${item.Name}`,
                            value: `${item.Name}`,
                        })
                    }
                    admin.brand_type_data = data_filter;
                    $('#val0Name').AutoComplete({
                        'data': data_filter,
                        'width': 280,
                        'itemHeight': 20,
                        'listStyle': 'custom',
                        'listDirection': 'down',
                        'createItemHandler': function (index, data) {
                            return `<p class="auto_list_p">${data.label}</p>`
                        },
                        'afterSelectedHandler': function (data) {
                            $('#val0').val(data.id)
                        },
                    });

                    let export_benefits = layui.data('orderClearance').data[31];
                    let data_filter_benefits = [];
                    for (let item of export_benefits) {
                        data_filter_benefits.push({
                            id: item.CustomsCode,
                            label: `${item.CustomsCode}-${item.Name}`,
                            value: `${item.Name}`,
                        })
                    }
                    admin.export_benefits_data = data_filter_benefits;
                    $('#val1Name').AutoComplete({
                        'data': data_filter_benefits,
                        'width': 280,
                        'itemHeight': 20,
                        'listStyle': 'custom',
                        'listDirection': 'down',
                        'createItemHandler': function (index, data) {
                            return `<p class="auto_list_p">${data.label}</p>`
                        },
                        'afterSelectedHandler': function (data) {
                            $('#val1').val(data.id)
                        },
                    });
                    ;
                    $('#elements').val(OrderItemsData[declaration_index].GModel);
                    const arrAnge = OrderItemsData[declaration_index].GModel.split('|');
                    arrAnge.forEach((value, index) => {
                        $(`#val${index}`).val(value)
                    });
                    admin.brand_type_data.forEach((value, index) => {
                        if (value.id == $('#val0').val()) {
                            $('#val0Name').val(value.value)
                        }
                    });
                    admin.export_benefits_data.forEach((value, index) => {
                        if (value.id == $('#val1').val()) {
                            $('#val1Name').val(value.value)
                        }
                    });
                    isOrderItemInsert = false;
                    break;

                case 'look':
                    if (!($('#CodeTS').val().trim())) {
                        return layer.msg('请先填写商品编码')
                    }
                    const hs_code_data_show = await admin.get(`/hs_code/get_hs_code_by_code/${OrderItemsData[declaration_index].CodeTS}`);
                    if (hs_code_data_show.data.length === 0) {
                        return layer.msg('此商品没有申报要素')
                    }
                    declaration_edit = false
                    const declaration_data_array_show = hs_code_data_show.data[0].declaration.split(';')
                    const data_show = declaration_data_array_show.map((item, index) => {
                        if (index < 9) {
                            return item.substr(1)
                        } else {
                            return item.substr(2)
                        }
                    })
                    laytpl($('#declaration_template').html()).render(data_show, function (html) {
                        $('#declaration_list').html(html)
                    })
                    layer.open({
                        type: 1,
                        title: '商品规范申报-商品申报要素',
                        shadeClose: true,
                        area: admin.screen() < 2 ? ['80%', '300px'] : ['1180px', '600px'],
                        content: `<div id="declaration_list_reload">${$('#declaration_list').html()}</div>`,
                        end: function () {
                            $('#g_qty').focus()
                        },
                    })
                    $('.manual_no_btn_next').show()
                    $('#declaration_save').hide()
                    $('.order_table_form_show input').each(function () {
                        $(this).attr('disabled', 'disabled')
                    })
                    $('#selectCodeTs').val(OrderItemsData[declaration_index].g_name)
                    $('#good_information').val(`${OrderItemsData[declaration_index].g_no}-${OrderItemsData[declaration_index].contr_item
                        ? OrderItemsData[declaration_index].contr_item
                        : '一般贸易'}-${OrderItemsData[declaration_index].g_name}`)
                    let brand_type_show = layui.data('orderClearance').data[30];
                    let data_filter_show = []
                    for (let item of brand_type_show) {
                        data_filter_show.push({
                            id: item.customs_code,
                            label: `${item.customs_code}-${item.name}`,
                            value: `${item.name}`,
                        })
                    }
                    admin.brand_type_data = data_filter_show
                    $('#val0Name').AutoComplete({
                        'data': data_filter_show,
                        'width': 280,
                        'itemHeight': 20,
                        'listStyle': 'custom',
                        'listDirection': 'down',
                        'createItemHandler': function (index, data) {
                            return `<p class="auto_list_p">${data.label}</p>`
                        },
                        'afterSelectedHandler': function (data) {
                            $('#val0').val(data.id)
                        },
                    })

                    let export_benefits_show = layui.data('orderClearance').data[31];
                    let data_filter_benefits_show = []
                    for (let item of export_benefits_show) {
                        data_filter_benefits_show.push({
                            id: item.customs_code,
                            label: `${item.customs_code}-${item.name}`,
                            value: `${item.name}`,
                        })
                    }
                    admin.export_benefits_data = data_filter_benefits_show
                    $('#val1Name').AutoComplete({
                        'data': data_filter_benefits_show,
                        'width': 280,
                        'itemHeight': 20,
                        'listStyle': 'custom',
                        'listDirection': 'down',
                        'createItemHandler': function (index, data) {
                            return `<p class="auto_list_p">${data.label}</p>`
                        },
                        'afterSelectedHandler': function (data) {
                            $('#val1').val(data.id)
                        },
                    })
                    $('#elements').val(OrderItemsData[declaration_index].g_model)
                    const arrAnge_show = OrderItemsData[declaration_index].g_model.split('|')
                    arrAnge_show.forEach((value, index) => {
                        $(`#val${index}`).val(value)
                    })
                    admin.brand_type_data.forEach((value, index) => {
                        if (value.id == $('#val0').val()) {
                            $('#val0Name').val(value.value)
                        }
                    })
                    admin.export_benefits_data.forEach((value, index) => {
                        if (value.id == $('#val1').val()) {
                            $('#val1Name').val(value.value)
                        }
                    })
                    isOrderItemInsert = false;
                    break
                case 'batch_edit':
                    if (checkData.length === 0) {
                        return layer.msg('请选择数据')
                    }
                    layer.open({
                        type: 1,
                        title: '商品批量修改',
                        shadeClose: true,
                        area: admin.screen() < 2 ? ['80%', '300px'] : ['680px', '550px'],
                        content: $('#batch_edit_list').html(),
                    });
                    $('#TradeCurrNameBatch').focus();
                    laydate.render({elem: '#ProdValidDtBatch', theme: '#1E9FFF', fixed: true});
                    laydate.render({elem: '#ProduceDateBatch', theme: '#1E9FFF', fixed: true});

                    /**自动完成--批量修改--币制**/
                    let currency = {
                        dataType: 'commonClearance',
                        type: 19,
                        name: '货币代码',
                        filter_type: 'l',
                        id: [
                            '#TradeCurrNameBatch',
                        ],
                        after: [
                            '#TradeCurrBatch',
                        ],
                    };
                    await admin.base_clearance_data_auto(currency);

                    /**自动完成--批量修改--原产国（地区）**/
                    let country_area = {
                        dataType: 'commonClearance',
                        type: 9,
                        name: '国别地区代码',
                        filter_type: 'l',
                        id: [
                            '#OriginCountryNameBatch',
                        ],
                        after: [
                            '#OriginCountryBatch',
                        ],
                    };
                    await admin.base_clearance_data_auto(country_area)

                    /**自动完成--批量修改--境内目的地代码**/  let domestic_area = {
                        dataType: 'orderClearance',
                        type: 14,
                        name: '国内地区代码',
                        filter_type: 's',
                        id: ['#DistrictCodeNameBatch'],
                        after: ['#DistrictCodeBatch'],
                    }
                    await admin.base_clearance_data_auto(domestic_area)

                    /**自动完成--征免方式**/
                    let exempting_method = {
                        dataType: 'commonClearance',
                        type: 4,
                        name: '征减免税方式代码',
                        filter_type: 's',
                        id: ['#DutyModeNameBatch'],
                        after: ['#DutyModeBatch'],
                    };
                    await admin.base_clearance_data_auto(exempting_method)

                    isOrderItemInsert = false;
                    break
            }
        });

        /**批量修改--货物属性**/
        $('body').on('click', '#GoodsAttrOpenBatch', async function () {
            const data = layui.data('orderClearance').data[22];
            const len = data.length;
            let result = []
            const sliceNum = 4
            for (let i = 0; i < len / sliceNum; i++) {
                result.push(data.slice(i * sliceNum, (i + 1) * sliceNum))
            }
            laytpl($('#goods_attr_batch_data_template').html()).render(result, function (html) {
                $('#goods_attr_batch_data_list').html(html)
            });
            const goods_attr_batch_index = layer.open({
                type: 1,
                title: '货物属性',
                shadeClose: true,
                area: admin.screen() < 2 ? ['80%', '300px'] : ['680px', '300px'],
                content: $('#goods_attr_batch_data_list').html(),
                success: function (layero, index) {
                    this.enterEsc = function (event) {
                        if (event.keyCode === 13) {
                            layer.close(goods_attr_batch_index);
                            return false
                        }
                    };
                    $(document).on('keydown', this.enterEsc)
                },
                end: function () {
                    $(document).off('keydown', this.enterEsc);
                    $('#stuff_batch').focus()
                },
            })

            $('.tableDiv_attr_batch_td').each(function () {
                const result = GoodsAttrBatchData.some(item => {
                    if (item.CustomsCode == $(this).data('id')) {
                        return true
                    }
                });
                if (result) {
                    $(this).addClass('bgcolor')
                }
            })
        });

        /**批量修改--货物属性选择**/
        $('body').on('click', '.tableDiv_attr_batch_td', function () {
            if ($(this).hasClass('bgcolor')) {
                $(this).removeClass('bgcolor')
            } else {
                $(this).addClass('bgcolor')
            }
            const result = GoodsAttrBatchData.some(item => {
                if (item.CustomsCode == $(this).data('id')) {
                    return true
                }
            });
            if (result) {
                const index = GoodsAttrBatchData.findIndex(item => item.CustomsCode == $(this).data('id'))
                GoodsAttrBatchData.splice(index, 1)
            } else {
                GoodsAttrBatchData.push({
                    CustomsCode: $(this).data('id'),
                    Name: $(this).attr('name'),
                })
            }
            const data = GoodsAttrBatchData.map(item => item.Name)
            $('#goods_attr_batch').val(data.join(','))
        })

        /**批量修改--征免方式回车**/
        $('body').on('keyup', '#duty_mode_name_batch', function (event) {
            const eCode = event.keyCode ? event.keyCode : event.which ? event.which : event.charCode
            if (event.shiftKey != 1 && eCode == 13) {
                $('#goods_attr_open_batch').click()
            }
        });

        /**批量修改--生产批次回车**/
        $('body').on('keyup', '#prod_batch_no_batch', function (event) {
            const eCode = event.keyCode ? event.keyCode : event.which ? event.which : event.charCode
            if (event.shiftKey != 1 && eCode == 13) {
                $('#batch_edit_save').click()
                return false
            }
        });

        /**批量修改--保存**/
        form.on('submit(batch_edit_save)', async (data) => {
            const checkData = table.checkStatus('order_pros').data
            const data_map = checkData.map(item => item.GNo)
            for (let item of data_map) {
                for (let value in data.field) {
                    if (value.indexOf('type') > -1) {
                        if (data.field[value]) {
                            const value_rep = value.replace('type_', '')
                            OrderItemsData[parseInt(item) - 1].GoodsSpecData[value_rep] = data.field[value]
                        }
                    } else {
                        if (data.field[value]) {
                            OrderItemsData[parseInt(item) - 1][value] = data.field[value]
                        }
                    }
                }
                if (GoodsAttrBatchData) {
                    OrderItemsData[parseInt(item) - 1].OrderItemGoodsAttr = GoodsAttrBatchData
                }
            }
            table.reload('order_pros', {
                data: OrderItemsData,
                limit: OrderItemsData.length,
            });
            layer.closeAll();
            for (let item of data_map) {
                $(`.layui-table-view[lay-id='order_pros'] .layui-table-body tr[data-index=${parseInt(item) - 1}] input`).prop('checked', true)
            }
            form.render('checkbox');
            $('#dec_users_submit').click()
        });


        async function last_dec(type) {
            if (declaration_index == 0) {
                return layer.msg('已经是第一条了')
            }
            declaration_index -= 1
            const hs_code_data_show = await admin.get(`/hs_code/get_hs_code_by_code/${OrderItemsData[declaration_index].CodeTS}`);
            const declaration_data_array_show = hs_code_data_show.data[0].declaration.split(';')
            const data_show = declaration_data_array_show.map((item, index) => {
                if (index < 9) {
                    return item.substr(1)
                } else {
                    return item.substr(2)
                }
            });
            laytpl($('#declaration_template').html()).render(data_show, function (html) {
                $('#declaration_list_reload').html(html)
            });

            if (type == 'look') {
                $('#declaration_next').attr('id', 'declaration_next_look')
                $('#declaration_last').attr('id', 'declaration_last_look')
            }
            submit_btn()
            form.render()

            $('#elements').focus()
            $('.manual_no_btn_next').show()
            $('.order_table_form_show input').each(function () {
                if (!declaration_edit) {
                    $(this).attr('disabled', 'disabled')
                }
                $(this).val('')
            })
            $('#selectCodeTs').val(OrderItemsData[declaration_index].g_name)
            $('#good_information').val(`${OrderItemsData[declaration_index].g_no}-${OrderItemsData[declaration_index].contr_item
                ? OrderItemsData[declaration_index].contr_item
                : '一般贸易'}-${OrderItemsData[declaration_index].g_name}`)
            let brand_type_show = layui.data('orderClearance').data[30];
            let data_filter_show = []
            for (let item of brand_type_show) {
                data_filter_show.push({
                    id: item.customs_code,
                    label: `${item.customs_code}-${item.name}`,
                    value: `${item.name}`,
                })
            }
            admin.brand_type_data = data_filter_show
            $('#val0Name').AutoComplete({
                'data': data_filter_show,
                'width': 280,
                'itemHeight': 20,
                'listStyle': 'custom',
                'listDirection': 'down',
                'createItemHandler': function (index, data) {
                    return `<p class="auto_list_p">${data.label}</p>`
                },
                'afterSelectedHandler': function (data) {
                    $('#val0').val(data.id)
                },
            })

            let export_benefits_show = layui.data('orderClearance').data[31];
            let data_filter_benefits_show = []
            for (let item of export_benefits_show) {
                data_filter_benefits_show.push({
                    id: item.customs_code,
                    label: `${item.customs_code}-${item.name}`,
                    value: `${item.name}`,
                })
            }
            admin.export_benefits_data = data_filter_benefits_show
            $('#val1Name').AutoComplete({
                'data': data_filter_benefits_show,
                'width': 280,
                'itemHeight': 20,
                'listStyle': 'custom',
                'listDirection': 'down',
                'createItemHandler': function (index, data) {
                    return `<p class="auto_list_p">${data.label}</p>`
                },
                'afterSelectedHandler': function (data) {
                    $('#val1').val(data.id)
                },
            })
            $('#elements').val(OrderItemsData[declaration_index].g_model)
            const arrAnge_show = OrderItemsData[declaration_index].g_model.split('|')
            arrAnge_show.forEach((value, index) => {
                $(`#val${index}`).val(value)
            })
            admin.brand_type_data.forEach((value, index) => {
                if (value.id == $('#val0').val()) {
                    $('#val0Name').val(value.value)
                }
            })
            admin.export_benefits_data.forEach((value, index) => {
                if (value.id == $('#val1').val()) {
                    $('#val1Name').val(value.value)
                }
            })
        }

        async function next_dec(type) {
            if ((declaration_index + 1) == OrderItemsData.length) {
                return layer.msg('已经是最后一条了')
            }
            declaration_index += 1
            const hs_code_data_show = await admin.get(`/hs_code/get_hs_code_by_code/${OrderItemsData[declaration_index].CodeTS}`);
            const declaration_data_array_show = hs_code_data_show.data[0].declaration.split(';')
            const data_show = declaration_data_array_show.map((item, index) => {
                if (index < 9) {
                    return item.substr(1)
                } else {
                    return item.substr(2)
                }
            })
            laytpl($('#declaration_template').html()).render(data_show, function (html) {
                $('#declaration_list_reload').html(html)
            })

            if (type == 'look') {
                $('#declaration_next').attr('id', 'declaration_next_look')
                $('#declaration_last').attr('id', 'declaration_last_look')
            }
            submit_btn()
            form.render()

            $('#elements').focus()
            $('.manual_no_btn_next').show()
            $('.order_table_form_show input').each(function () {
                if (!declaration_edit) {
                    $(this).attr('disabled', 'disabled')
                }
                $(this).val('')
            })
            $('#selectCodeTs').val(OrderItemsData[declaration_index].g_name)
            $('#good_information').val(`${OrderItemsData[declaration_index].g_no}-${OrderItemsData[declaration_index].contr_item
                ? OrderItemsData[declaration_index].contr_item
                : '一般贸易'}-${OrderItemsData[declaration_index].g_name}`)
            let brand_type_show = await admin.get(`/clearance/no_paginate?type=品牌类型`)
            let data_filter_show = []
            for (let item of brand_type_show) {
                data_filter_show.push({
                    id: item.customs_code,
                    label: `${item.customs_code}-${item.name}`,
                    value: `${item.name}`,
                })
            }
            admin.brand_type_data = data_filter_show
            $('#val0Name').AutoComplete({
                'data': data_filter_show,
                'width': 280,
                'itemHeight': 20,
                'listStyle': 'custom',
                'listDirection': 'down',
                'createItemHandler': function (index, data) {
                    return `<p class="auto_list_p">${data.label}</p>`
                },
                'afterSelectedHandler': function (data) {
                    $('#val0').val(data.id)
                },
            })

            let export_benefits_show = await admin.get(`/clearance/no_paginate?type=出口享惠情况`)
            let data_filter_benefits_show = []
            for (let item of export_benefits_show) {
                data_filter_benefits_show.push({
                    id: item.customs_code,
                    label: `${item.customs_code}-${item.name}`,
                    value: `${item.name}`,
                })
            }
            admin.export_benefits_data = data_filter_benefits_show
            $('#val1Name').AutoComplete({
                'data': data_filter_benefits_show,
                'width': 280,
                'itemHeight': 20,
                'listStyle': 'custom',
                'listDirection': 'down',
                'createItemHandler': function (index, data) {
                    return `<p class="auto_list_p">${data.label}</p>`
                },
                'afterSelectedHandler': function (data) {
                    $('#val1').val(data.id)
                },
            })
            $('#elements').val(OrderItemsData[declaration_index].g_model)
            const arrAnge_show = OrderItemsData[declaration_index].g_model.split('|')
            arrAnge_show.forEach((value, index) => {
                $(`#val${index}`).val(value)
            })
            admin.brand_type_data.forEach((value, index) => {
                if (value.id == $('#val0').val()) {
                    $('#val0Name').val(value.value)
                }
            })
            admin.export_benefits_data.forEach((value, index) => {
                if (value.id == $('#val1').val()) {
                    $('#val1Name').val(value.value)
                }
            })
        }


        /**集装箱**/
        let ContaineremptyObj = {
            formID: "order_containers_form",
            focusId: "ContainerId",
            tableName: "order_containers_table",
            datas: null,
            index: null,
        };

        /**集装箱--商品序号默认全选**/
        $('body').on('keyup', '#ContainerId', function (event) {
            const eCode = event.keyCode ? event.keyCode : event.which ? event.which : event.charCode
            if (event.shiftKey != 1 && eCode == 13) {
                if (OrderItemsData.length > 0) {
                    const data = OrderItemsData.map(item => item.GNo)
                    $('#GoodsNo').val(data.join(','))
                }
            }
        });

        /**集装箱--点击行反填数据**/
        table.on('row(order_containers_table)', function (obj) {
            ContaineremptyObj.index = obj.tr.data("index")
            for (let item in obj.data) {
                if (item == 'Id') {
                    $(`#OrderContainerId`).val(obj.data[item])
                } else {
                    $(`#${item}`).val(obj.data[item])
                }
            }
            $('#ContainerId').focus()
        });

        /**集装箱--保存**/
        form.on('submit(order_containers_submit)', async (data) => {
            data.field.OrderId = order_id;
            let orderContainerId = data.field.OrderContainerId;
            if (orderContainerId && orderContainerId != '0') {
                let result = await admin.patch(`/order_container/update/${orderContainerId}`, data.field);
                if (result.status) {
                    OrderContainers.splice(ContaineremptyObj.index, 1, result.obj)
                }
            } else {
                let result = await admin.post('/order_container/store', data.field);
                if (result.status) {
                    OrderContainers.push(result.obj)
                }
            }

            ContaineremptyObj.datas = OrderContainers;
            setOrderRelationEmpty(ContaineremptyObj);
        });

        /**集装箱--删除**/
        table.on('toolbar(order_containers_table)', function (obj) {
            let checkStatus = table.checkStatus(obj.config.id);
            let checkData = checkStatus.data;
            switch (obj.event) {
                case 'add':
                    setOrderRelationEmpty(ContaineremptyObj);
                    break;
                case 'delete':
                    if (checkData.length === 0) {
                        return layer.msg('请选择数据')
                    }
                    layer.confirm('真的删除么', {title: '提示'}, async (index) => {
                        let delData = admin.getDelIds(OrderContainers, checkData);
                        let result = await admin.post(`/order_container/delete/`, JSON.stringify({
                            Ids: delData.Ids,
                        }));

                        if (result.status) {
                            ContaineremptyObj.datas = delData.Datas;
                            setOrderRelationEmpty(ContaineremptyObj);
                        }
                    })
                    break
            }
        })

        /**集装箱--按enter保存**/
        $('body').on('keyup', '#GoodsNo', function (event) {
            const eCode = event.keyCode ? event.keyCode : event.which ? event.which : event.charCode
            if (event.shiftKey != 1 && eCode == 13) {
                $('#order_containers_submit').click();
                $('#ContainerId').focus()
            }
        })

        /**集装箱--商品序号关系列表**/
        $('body').on('click', '#goods_no_open', function () {
            layer.open({
                type: 1,
                title: '商品序号关系',
                shadeClose: true,
                area: admin.screen() < 2 ? ['80%', '300px'] : ['910px', '480px'],
                content: $('#goods_no_list').html(),
                success: function (layero, index) {
                    this.enterEsc = function (event) {
                        if (event.keyCode === 13) {
                            $('#goods_no_save').click();
                            return false
                        }
                    }
                    $(document).on('keydown', this.enterEsc)
                },
                end: function () {
                    $(document).off('keydown', this.enterEsc)
                },
            })

            const check_data = $('#GoodsNo').val().split(',').map(Number)
            table.render({
                elem: '#goods_no_table'
                , toolbar: true
                , defaultToolbar: ['filter']
                , colFilterRecord: 'local'
                , primaryKey: 'GNo'
                , checkStatus: {
                    default: check_data,
                }
                , cols: [
                    [
                        {type: 'checkbox'}
                        , {field: 'GNo', title: '序号', width: 100}
                        , {field: 'CodeTS', title: '商品编号'}
                        , {field: 'GName', title: '商品名称'},
                    ]]
                , data: OrderItemsData
                , limit: OrderItemsData.length
                , height: 350,
            })
        })

        /**集装箱--商品序号关系列表--保存**/
        $('body').on('click', '#goods_no_save', function () {
            let checkData = table.checkStatus('goods_no_table').data;
            const data = checkData.map(item => item.GNo);
            $('#GoodsNo').val(data.join(','));
            $('#GoodsNo').focus();
            layer.closeAll()
        })

        /**随附单证**/
        let emptyObj = {
            formID: "order_documents_form",
            focusId: "DocuCodeName",
            tableName: "order_documents_table",
            datas: OrderDocuments,
            index: null,
        }


        /**随附单证--点击行反填数据**/
        table.on('row(order_documents_table)', function (obj) {
            for (let item in obj.data) {
                if (item == 'Id') {
                    $(`#OrderDocumentId`).val(obj.data[item])
                } else {
                    $(`#${item}`).val(obj.data[item])
                }
            }
            emptyObj.index = obj.tr.data("index")
            $('#DocuCodeName').focus()
        })

        /**随附单证--保存**/
        form.on('submit(order_documents_submit)', async (data) => {
            data.field.OrderId = order_id;
            let orderDocumentId = data.field.OrderDocumentId;
            if (orderDocumentId && orderDocumentId != '0') {
                let result = await admin.patch(`/order_document/update/${orderDocumentId}`, data.field)
                if (result.status) {
                    OrderDocuments.splice(emptyObj.index, 1, result.obj)
                }
            } else {
                let result = await admin.post('/order_document/store', data.field)
                if (result.status) {
                    OrderDocuments.push(result.obj)
                }
            }
            setOrderRelationEmpty(emptyObj);
        })
        /**随附单证--操作按钮**/
        /**原产地对应关系录入--key**/
        table.on('toolbar(order_documents_table)', function (obj) {
            let checkStatus = table.checkStatus(obj.config.id);
            let checkData = checkStatus.data
            switch (obj.event) {
                case 'add':
                    setOrderRelationEmpty(emptyObj);
                    break
                case 'delete':
                    if (checkData.length === 0) {
                        return layer.msg('请选择数据')
                    }
                    layer.confirm('真的删除么', {title: '提示'}, async (index) => {
                        let delData = admin.getDelIds(OrderDocuments, checkData);
                        let result = await admin.post(`/order_document/delete/`, JSON.stringify({
                            Ids: delData.Ids,
                        }));

                        if (result.status) {
                            emptyObj.datas = delData.Datas;
                            setOrderRelationEmpty(emptyObj);
                        }
                    })
                    break
            }
        })

        /**随附单证--按enter保存**/
        $('body').on('keyup', '#CertCode', function (event) {
            const eCode = event.keyCode ? event.keyCode : event.which ? event.which : event.charCode;
            if (event.shiftKey != 1 && eCode == 13) {
                const acmpFormCode = $('#DocuCode').val();
                if ($.inArray(acmpFormCode, ['Y', 'E', 'R', 'F', 'J']) < 0) {
                    $('#order_documents_submit').click();
                    $('#DocuCodeName').focus()
                } else {
                    $('#order_documents_submit').click()
                }
            }
        })

        /**随附单证--按enter判断不能有重复的随附单证代码**/
        $('body').on('keyup', '#DocuCodeName', function (event) {
            const eCode = event.keyCode ? event.keyCode : event.which ? event.which : event.charCode
            let docu_code_name = 0
            if (event.shiftKey != 1 && eCode == 13) {
                if (OrderDocuments.length > 0) {
                    for (let item of OrderDocuments) {
                        if (item.docu_code_name == $('#DocuCodeName').val()) {
                            docu_code_name = 1
                        }
                    }
                    if (docu_code_name) {
                        $('#DocuCodeName').val('')
                        $('#DocuCodeName').focus()
                        return layer.msg('随附单证代码不可重复!')
                    }
                }
            }
        });

        /**报关整合申报保存**/
        form.on('submit(order_save)', async (data) => {
            if (OrderItemsData.length > 0) {
                if (!(data.field.NetWt)) {
                    return layer.msg('存在表体商品且是千克，必填净重！')
                }

                let total = 0
                for (let item of OrderItemsData) {
                    if (item.GUnit == '035') {
                        total += parseFloat(item.GQty) * 100000
                    } else if (item.FirstUnit == '035') {
                        total += parseFloat(item.FirstQty) * 100000
                    } else if (item.SecondUnit == '035') {
                        total += parseFloat(item.SecondQty) * 100000
                    }
                }

                if (admin.cutZero((total / 100000).toString()) != admin.cutZero(data.field.NetWt.toString())) {
                    // if (!no_weight_save) {
                    //   layer.open({
                    //     title: '商品总重量与净重不符'
                    //     , content: '商品总重量与净重不符！是否要保存'
                    //     , btn: ['是', '否']
                    //     , yes: function (index) {
                    //       no_weight_save = true
                    //       layer.close(index)
                    //       $('#order_save').click()
                    //     }
                    //     , btn2: function () {
                    //       layer.msg('请重新修改净重。')
                    //       $('#NetWt').focus()
                    //     },
                    //   })
                    //   if (!no_weight_save) {
                    //     return false
                    //   }
                    // }
                }
            }

            // layer.load(2);

            /**企业承诺**/
            data.field.DeclaratioMaterialCode = DeclaratioMaterialCode
            /**企业资质**/
            data.field.EntQualifTypes = JSON.stringify(EntQualifData)
            /**检验检疫签证申报要素**/
            data.field.DecRequestCerts = JSON.stringify(DecRequestCertsData)
            /**使用人数据**/
            data.field.DecUsers = JSON.stringify(DecUsersData)
            /**特殊业务标识数据**/
            data.field.SpecDeclFlag = JSON.stringify(SpecDeclFlag)
            /**业务选项**/
            let promiseItmes = []
            /**特殊关系确认**/
            if (!(data.field['PromiseItmes[0]'])) {
                if ($('#PromiseItmes0').data('first') == '1') {
                    promiseItmes.push('0')
                } else {
                    promiseItmes.push('9')
                }
            } else {
                delete data.field['PromiseItmes[0]']
                promiseItmes.push('1')
            }

            /**价格影响确认**/
            if (!(data.field['PromiseItmes[1]'])) {
                if ($('#PromiseItmes1').data('first') == '1') {
                    promiseItmes.push('0')
                } else {
                    promiseItmes.push('9')
                }
            } else {
                delete data.field['PromiseItmes[1]']
                promiseItmes.push('1')
            }
            /**支付特权使用费确认**/
            if (!(data.field['PromiseItmes[2]'])) {
                if ($('#PromiseItmes2').data('first') == '1') {
                    promiseItmes.push('0')
                } else {
                    promiseItmes.push('9')
                }
            } else {
                delete data.field['PromiseItmes[2]']
                promiseItmes.push('1')
            }
            data.field.PromiseItmes = JSON.stringify(promiseItmes)
            // 业务事项
            data.field.Type = data.field['Type[1]'];
            // 原箱运输
            if (!(data.field['OrigBoxFlag'])) {
                data.field.OrigBoxFlag = 0
            }
            /**异地报关**/
            if ($('#IsOther').prop('checked')) {
                data.field.IsOther = 1
            } else {
                data.field.IsOther = 0
            }

            if (!order_id) {
                const result = await admin.post(`/order/store/` + ieflag, data.field);
                if (result.status) {
                    setTimeout(() => {
                        isSaved = true;
                        admin.reloadFrame(iEFlagName + '报关整合申报iframe');
                        window.location.href = '/order/edit/' + result.obj.Id
                    }, 150)
                }
            } else {
                const result = await admin.patch(`/order/update/${order_id}`, data.field);
                if (result.status) {
                    setTimeout(() => {
                        isSaved = true;
                        admin.reloadFrame(iEFlagName + '报关整合申报iframe');
                    }, 150)
                }
            }
            layer.closeAll('loading')
        });

        /**打印**/
        $('body').on('click', '#order_print', async function () {
            if (!order_id) {
                return layer.msg('请先保存订单！')
            }
            layer.open({
                type: 1,
                title: '打印',
                shadeClose: true,
                area: admin.screen() < 2 ? ['80%', '300px'] : ['1020px', '580px'],
                content: $('#print_lists_template').html(),
            })
            layer.load(2)
            await admin.getPdf(order_id, 'e', admin.order_e_print_list)
            table.render({
                elem: '#print_lists'
                , data: admin.order_e_print_list
                , cols: [
                    [
                        {
                            field: 'name', title: '类型', templet: function (data) {
                                if (data.is_enclosure) {
                                    return `<p>${data.name}<span class="enclosure_span">附件</span></p>`
                                } else {
                                    return data.name
                                }
                            },
                        }
                        , {title: '操作', toolbar: '#print_toolbar', width: 280},
                    ]]
                , limit: admin.order_e_print_list.length,
            })
        })
        /**打印按钮操作**/
        let print_edit_index, file_type_id, orientation_save, save_pdf_id
        table.on('tool(print_lists)', async function (obj) {
            switch (obj.event) {
                case 'preview':
                    order.print_preview(obj, order_id, order_i_edit_data, 'e')
                    break
                case 'download':
                    order.print_download(obj, order_id, order_i_edit_data, 'e')
                    break
                case 'enclosure_save':
                    order.print_enclosure_save(obj, order_id, order_i_edit_data, 'e', admin.order_e_print_list)
                    break
                case 'reload_save':
                    order.print_reload_save(obj, order_id, order_i_edit_data, 'e', admin.order_e_print_list)
                    break
                case 'null_download':
                    layer.msg('请先保存附件')
                    break
            }
        })
        /**打印前修改-合同-预览**/
        form.on('submit(print_edit_contract_save)', async (data) => {
            order.print_edit_contract_save(data, order_id, 'e')
        })
        /**打印前修改-发票-预览**/
        form.on('submit(print_edit_invoice_save)', async (data) => {
            order.print_edit_invoice_save(data, order_id, 'e')
        })
        /**打印前修改-司机纸-预览**/
        form.on('submit(print_edit_driver_save)', async (data) => {
            order.print_edit_driver_save(data, order_id, 'e')
        })
        /**保存前修改-合同-保存**/
        form.on('submit(print_save_contract_save)', async (data) => {
            order.print_save_contract_save(data, order_id, 'e', admin.order_e_print_list)
        })
        /**保存前修改-发票-保存**/
        form.on('submit(print_save_invoice_save)', async (data) => {
            order.print_save_invoice_save(data, order_id, 'e', admin.order_e_print_list)
        })
        /**保存前修改-司机纸-保存**/
        form.on('submit(print_save_driver_save)', async (data) => {
            order.print_save_driver_save(data, order_id, 'e', admin.order_e_print_list)
        })
        /**附注**/
        $('body').on('click', '#order_note', async function () {
            if (!order_id) {
                return layer.msg('请先保存订单！')
            }
            order_note_index = layer.open({
                type: 1,
                title: '附注',
                shadeClose: true,
                area: admin.screen() < 2 ? ['80%', '300px'] : ['650px', '340px'],
                content: $('#remark_note_template').html(),
            })
            form.render()
            if (order_note_data) {
                $('#remark_note').val(order_note_data)
            }
            $('#order_note_dot').hide()
        })

        $('body').on('input', '#remark_note', function () {
            $('#remark_note_number span').text($(this).val().length)
        })
        /**附注保存**/
        form.on('submit(remark_note_submit)', async (data) => {
            order_note_data = data.field.remark
            await admin.post(`/order/e/${order_id}/remark`, data.field)
            layer.close(order_note_index)
        })

        /**导入**/
        const upload_order_i = upload.render({
            elem: '#order_i_import'
            ,
            url: '/order/e/import'
            ,
            accept: 'file'
            ,
            acceptMime: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.ms-excel,application/vnd.ms-excel.sheet.macroEnabled.12'
            ,
            exts: 'xlsx|xls|xlsm'
            ,
            field: 'order_file'
            ,
            data: {
                OrderId: order_id,
            }
            ,
            before: function (obj) {
                layer.load(2)
            }
            ,
            done: async function (res) {
                if (res.status) {
                    layer.msg(res.msg, {
                        offset: '15px'
                        , icon: 1
                        , time: 2000
                        , id: 'Message',
                    })
                } else {
                    layer.msg(res.msg, {
                        offset: '15px'
                        , icon: 2
                        , time: 2000
                        , id: 'Message',
                    })
                }
                layer.closeAll('loading')
                await order_i_edit_back_filling(res.data)
                if ($('#manual_no').val().trim()) {
                    const data = await admin.get(`/order/account_manual_once?name=${$('#manual_no').val()}`)
                    if (data === '') {
                        layer.msg(`备案号：${$('#manual_no').val()} 不存在！2`, {
                            offset: '15px'
                            , icon: 2
                            , time: 1000
                            , id: 'Message',
                        })
                    } else {
                        admin.materials_data = data.materials.data
                        admin.goods_data = data.goods.data

                        $('#contr_item').removeAttr('disabled', 'disabled')
                        $('#trade_code').attr('disabled', 'disabled')
                        $('#owner_code').attr('disabled', 'disabled')
                        $('#duty_mode').val('3')
                        $('#duty_mode_name').val('全免')
                        if (data.company_client_code.substring(0, 5) == '44199') {
                            $('#district_code').val('44199')
                            $('#district_code_name').val('东莞')
                        }
                    }
                }
                admin.transModeControl(ieflag)
                if (order_i_edit_data.company) {
                    $('#order_dispatch').data('user', order_i_edit_data.company.user_id)
                }
            }
            ,
            error: function () {
                layer.closeAll('loading')
            },
        })

        /** 复制订单数据 **/
        $('body').on('click', '#order_copy_data', function () {
            layer.open({
                type: 1,
                title: '复制订单数据',
                area: ['500px', '200px'],
                fixed: false,
                content: $('#check_order_template'),
                btn: ['确定', '取消'],
                yes: function () {
                    get_copy_data()
                },
                btn2: function () {
                    layer.closeAll()
                },
            })

            async function get_copy_data() {
                let copy_all_data = await admin.post(`/order/e/copy_order_data/`, {client_seq_no: $('#copy_order_id').val()})

                if (copy_all_data.status) {
                    setTimeout(async () => {
                        layer.closeAll()
                        layer.load(2)

                        let reset_order_pro = []
                        for (let item_apply of order_i_edit_data.pros) {
                            if (item_apply.id) {
                                reset_order_pro.push(item_apply.id)
                            }
                        }

                        let reset_order_containers = []
                        for (let item_apply of order_i_edit_data.containers) {
                            if (item_apply.id) {
                                reset_order_containers.push(item_apply.id)
                            }
                        }

                        order_status = order_i_edit_data.order_status_string
                        order_i_edit_data = copy_all_data.data
                        order_i_edit_data.client_seq_no = $('#client_seq_no').val()
                        order_i_edit_data.foreign_company_name = $('#foreign_company_name').val()
                        order_i_edit_data.manual_no = $('#manual_no').val()
                        order_i_edit_data.contr_no = $('#contr_no').val()
                        order_i_edit_data.i_e_date = $('#i_e_date').val()
                        order_i_edit_data.apl_date = $('#apl_date').val()
                        order_i_edit_data.trade_co_scc = $('#trade_co_scc').val()
                        order_i_edit_data.trade_code = $('#trade_code').val()
                        order_i_edit_data.trade_name = $('#trade_name').val()
                        order_i_edit_data.owner_code_scc = $('#owner_code_scc').val()
                        order_i_edit_data.owner_code = $('#owner_code').val()
                        order_i_edit_data.owner_name = $('#owner_name').val()
                        order_i_edit_data.agent_code_scc = $('#agent_code_scc').val()
                        order_i_edit_data.agent_code = $('#agent_code').val()
                        order_i_edit_data.decl_ciq_code = $('#decl_ciq_code').val()
                        order_i_edit_data.agent_name = $('#agent_name').val()
                        order_i_edit_data.order_status_string = order_status

                        await order_i_edit_back_filling(order_i_edit_data)

                        order_i_edit_data.id = order_id

                        for (let k = 0; k < order_i_edit_data.pros.length; k++) {
                            if (order_i_edit_data.pros[k].order_id) {
                                order_i_edit_data.pros[k].order_id = ''
                            }
                            order_i_edit_data.pros[k].id = ''
                        }

                        for (let k = 0; k < order_i_edit_data.containers.length; k++) {
                            if (order_i_edit_data.containers[k].order_id) {
                                order_i_edit_data.containers[k].order_id = ''
                            }
                            order_i_edit_data.containers[k].id = ''
                        }

                        $('#apl_date').val(order_i_edit_data.apl_date)
                        if ($('#manual_no').val().trim()) {
                            const data = await admin.get(`/order/account_manual_once?name=${$('#manual_no').val()}`)
                            if (data === '') {
                                layer.msg(`备案号：${$('#manual_no').val()} 不存在！3`, {
                                    offset: '15px'
                                    , icon: 2
                                    , time: 1000
                                    , id: 'Message',
                                })
                            } else {
                                admin.materials_data = data.materials.data
                                admin.goods_data = data.goods.data

                                $('#contr_item').removeAttr('disabled', 'disabled')
                                $('#trade_code').attr('disabled', 'disabled')
                                $('#owner_code').attr('disabled', 'disabled')
                                $('#duty_mode').val('3')
                                $('#duty_mode_name').val('全免')
                                if (data.CompanyClientCode.substring(0, 5) == '44199') {
                                    $('#district_code').val('44199')
                                    $('#district_code_name').val('东莞')
                                }
                            }
                        }
                        admin.transModeControl(ieflag)
                        if (order_i_edit_data.company) {
                            $('#order_dispatch').data('user', order_i_edit_data.company.user_id)
                        }

                        admin.order_pros_delete_ids = reset_order_pro

                    }, 1000)
                }
            }
        });

        /**审核通过**/
        form.on('submit(order_save_pass)', async (data) => {
            console.log("order_save_pass");
            if (OrderItemsData.length === 0) {
                return layer.msg('请先输入表体商品')
            }
            if (data.field.NetWt) {
                if (OrderItemsData.length === 0) {
                    return layer.msg('存在净重，必须填写表体商品！')
                }
            }

            let result = await admin.get(`/order/audit/` + order_id);
            if (result.status) {
                setTimeout(() => {
                    admin.reloadFrame(iEFlagName + '报关整合申报iframe');
                }, 150)
            }

            layer.closeAll('loading')
        });

        /**派单**/
        admin.distribute('#order_dispatch', order_id, iEFlagName + '报关整合申报iframe', "order");
        /**附件**/
        $('body').on('click', '#order_enclosure', function () {
            if (!order_id) {
                return layer.msg('请先保存订单！')
            }
            layer.open({
                type: 1,
                title: '附件',
                shadeClose: true,
                area: admin.screen() < 2 ? ['80%', '300px'] : ['1020px', '600px'],
                content: $('#order_enclosure_template').html(),
            })
            table.render({
                elem: '#order_enclosure_lists'
                , skin: 'line'
                , url: `/order/e/${order_id}/pdf/lists?sortedBy=desc&orderBy=created_at`
                , response: {
                    countName: 'total',
                }
                , cols: [
                    [
                        {field: 'edoc_code_name', title: '类型', width: 150}
                        , {field: 'edoc_cop_id', title: '文件名称'}
                        , {field: 'creator', title: '操作人', width: 120}
                        , {field: 'version', title: '版本号', width: 120}
                        , {field: 'created_at', title: '上传时间'}
                        , {title: '操作', toolbar: '#order_enclosure_toolbar', width: 280},
                    ]]
                , page: true
                , limit: 10,
            })
        });

        /**新增附件**/
        let order_enclosure_data = []
            , order_enclosure_upload
            , add_enclosure_index
            , demoListView
            , demoListView_tr
        $('body').on('click', '#add_enclosure', function () {
            add_enclosure_index = layer.open({
                type: 1,
                title: '新增附件',
                shadeClose: true,
                area: admin.screen() < 2 ? ['80%', '300px'] : ['1020px', '500px'],
                content: $('#order_enclosure_template_add').html(),
                end: function () {
                    order_enclosure_data = []
                },
            })
            /**附件上传**/
            order_enclosure_upload = upload.render({
                elem: '#order_enclosure_upload'
                , url: '/image/pdf/upload'
                , accept: 'file'
                , data: {
                    OrderId: order_id,
                }
                , size: 1024 * admin.UPLOAD_PDF_SIZE
                , multiple: true
                , auto: true
                , bindAction: '#order_enclosure_upload_action'
                , field: 'pdf'
                , before: function (obj) {
                    layer.load(2)
                }
                , choose: function (obj) {
                    demoListView = $('#order_enclosure_upload_list')
                    if (!edoc_code) {
                        layer.msg('请先选择类型')
                        order_enclosure_upload.config.elem.next()[0].value = ''
                        return
                    }
                    if (edoc_code != 'local_2') {
                        if (demoListView[0].childNodes.length === 1) {
                            layer.msg('只能选择一个文件')
                            order_enclosure_upload.config.elem.next()[0].value = ''
                            return
                        }
                    }
                    let files = this.files = obj.pushFile()
                    obj.preview(function (index, file, result) {
                        demoListView_tr = $([
                            '<tr id="upload-' + index + '">'
                            ,
                            '<td>' + file.name + '</td>'
                            ,
                            '<td>' + (file.size / 1014).toFixed(1) + 'kb</td>'
                            ,
                            '<td>等待上传</td>'
                            ,
                            '<td>'
                            ,
                            '<button class="layui-btn custom-create_btn test-upload-demo-reload layui-hide" type="button">重传</button>'
                            ,
                            `<button class="layui-btn layui-btn-mini layui-btn-danger test-upload-demo-delete" data-index="${index}" type="button">删除</button>`
                            ,
                            '</td>'
                            ,
                            '</tr>'].join(''))
                        demoListView_tr.find('.test-upload-demo-reload').on('click', function () {
                            obj.upload(index, file)
                        })
                        demoListView_tr.find('.test-upload-demo-delete').on('click', function () {
                            delete files[index]
                            demoListView_tr.remove()
                            order_enclosure_upload.config.elem.next()[0].value = ''
                            order_enclosure_data.forEach((value, key) => {
                                if (value.index == $(this).data('index')) {
                                    order_enclosure_data.splice(key, 1)
                                }
                            })
                        })
                        demoListView.append(demoListView_tr)
                    })
                }
                , done: function (res, index, upload) {
                    if (res.status) {
                        layer.msg('上传成功', {
                            offset: '15px'
                            , icon: 1
                            , time: 1000
                            , id: 'Message',
                        })
                        order_enclosure_data.push({
                            index: index,
                            ...res,
                        })
                        let tr = demoListView.find('tr#upload-' + index)
                            , tds = tr.children()
                        tds.eq(2).html('<span style="color: #5FB878;">上传成功</span>')
                        tds.eq(3).find('.test-upload-demo-reload').addClass('layui-hide')
                        layer.closeAll('loading')
                        return delete this.files[index]
                    } else {
                        layer.msg(res.msg, {
                            offset: '15px'
                            , icon: 2
                            , time: 1000
                            , id: 'Message',
                        })
                    }
                    layer.closeAll('loading')
                    this.error(index, upload)
                }
                , error: function (index, upload) {
                    let tr = demoListView.find('tr#upload-' + index)
                        , tds = tr.children()
                    tds.eq(2).html('<span style="color: #FF5722;">上传失败</span>')
                    tds.eq(3).find('.test-upload-demo-reload').removeClass('layui-hide')
                    layer.closeAll('loading')
                },
            })
            form.render()
        })
        /**选择附件类型**/
        form.on('select(edoc_code)', function (data) {
            const data_value = data.value.split(',')
            edoc_code = data_value[0]
            edoc_code_name = data_value[1]
        })
        /**编辑附件-选择附件类型**/
        form.on('select(edoc_code_edit)', function (data) {
            const data_value = data.value.split(',')
            edoc_code = data_value[0]
            edoc_code_name = data_value[1]
        })
        /**新建附件**/
        form.on('submit(order_enclosure_submit)', async function (data) {
            if (order_enclosure_data.length === 0) {
                layer.msg('请先上传文件')
            }
            if (edoc_code != 'local_2') {
                if (order_enclosure_data.length > 1) {
                    layer.msg('只能选择一个文件')
                    return
                }
                const form_data = [
                    {
                        edoc_code: edoc_code,
                        edoc_code_name: edoc_code_name,
                        edoc_cop_id: order_enclosure_data[0].edoc_cop_id,
                        edoc_cop_url: order_enclosure_data[0].edoc_cop_url,
                    }]
                const res = await admin.post(`/order/e/${order_id}/pdf/create`, {
                    data: form_data,
                })
                if (res.status) {
                    layer.close(add_enclosure_index)
                    table.reload('order_enclosure_lists')
                }
            } else {
                const form_data = {
                    edoc_code: edoc_code,
                    edoc_code_name: edoc_code_name,
                }
                order_enclosure_data.forEach((value, index) => {
                    delete value.status
                    delete value.edoc_size
                    value.edoc_code = edoc_code
                    value.edoc_code_name = edoc_code_name
                })
                const res = await admin.post(`/order/e/${order_id}/pdf/create`, {
                    data: order_enclosure_data,
                })
                if (res.status) {
                    layer.close(add_enclosure_index)
                    table.reload('order_enclosure_lists')
                }
            }
        })
        /**附件按钮操作**/
        let order_enclosure_data_edit = []
            , order_enclosure_upload_edit
            , edit_enclosure_index
            , demoListView_edit
            , demoListView_tr_edit
            , order_enclosure_id
        table.on('tool(order_enclosure_lists)', async function (obj) {
            switch (obj.event) {
                case 'preview':
                    const preview_data = await admin.get(`/order/e/pdf/${obj.data.id}/show`)
                    window.open(preview_data)
                    break
                case 'download':
                    window.open(`/order/e/pdf/${obj.data.id}/downloads`)
                    break
                case 'edit':
                    order_enclosure_id = obj.data.id
                    edit_enclosure_index = layer.open({
                        type: 1,
                        title: '编辑附件',
                        shadeClose: true,
                        area: admin.screen() < 2 ? ['80%', '300px'] : ['1020px', '500px'],
                        content: $('#order_enclosure_template_edit').html(),
                        end: function () {
                            order_enclosure_data_edit = []
                        },
                    })
                    /**附件上传**/
                    order_enclosure_upload_edit = upload.render({
                        elem: '#order_enclosure_upload_edit'
                        , url: '/image/pdf/upload'
                        , accept: 'file'
                        , data: {
                            OrderId: order_id,
                        }
                        , size: 1024 * admin.UPLOAD_PDF_SIZE
                        , multiple: true
                        , auto: true
                        , bindAction: '#order_enclosure_upload_action_edit'
                        , field: 'pdf'
                        , before: function (obj) {
                            layer.load(2)
                        }
                        , choose: function (obj) {
                            demoListView_edit = $('#order_enclosure_upload_list_edit')
                            if (!edoc_code) {
                                layer.msg('请先选择类型')
                                order_enclosure_upload_edit.config.elem.next()[0].value = ''
                                return
                            }
                            if (demoListView_edit[0].childNodes.length === 1) {
                                layer.msg('只能选择一个文件')
                                order_enclosure_upload_edit.config.elem.next()[0].value = ''
                                return
                            }
                            let files = this.files = obj.pushFile()
                            obj.preview(function (index, file, result) {
                                demoListView_tr_edit = $([
                                    '<tr id="upload-' + index + '">'
                                    ,
                                    '<td>' + file.name + '</td>'
                                    ,
                                    '<td>' + (file.size / 1014).toFixed(1) + 'kb</td>'
                                    ,
                                    '<td>等待上传</td>'
                                    ,
                                    '<td>'
                                    ,
                                    '<button class="layui-btn custom-create_btn test-upload-demo-reload layui-hide" type="button">重传</button>'
                                    ,
                                    `<button class="layui-btn layui-btn-mini layui-btn-danger test-upload-demo-delete" data-index="${index}" type="button">删除</button>`
                                    ,
                                    '</td>'
                                    ,
                                    '</tr>'].join(''))
                                demoListView_tr_edit.find('.test-upload-demo-reload').on('click', function () {
                                    obj.upload(index, file)
                                })
                                demoListView_tr_edit.find('.test-upload-demo-delete').on('click', function () {
                                    delete files[index]
                                    demoListView_tr_edit.remove()
                                    order_enclosure_upload_edit.config.elem.next()[0].value = ''
                                    order_enclosure_data_edit.forEach((value, key) => {
                                        if ($(this).data('id')) {
                                            if (value.id == $(this).data('id')) {
                                                order_enclosure_data_edit.splice(key, 1)
                                            }
                                        } else {
                                            if (value.index == $(this).data('index')) {
                                                order_enclosure_data_edit.splice(key, 1)
                                            }
                                        }
                                    })
                                })
                                demoListView_edit.append(demoListView_tr_edit)
                            })
                        }
                        , done: function (res, index, upload) {
                            if (res.status) {
                                layer.msg('上传成功', {
                                    offset: '15px'
                                    , icon: 1
                                    , time: 1000
                                    , id: 'Message',
                                })
                                order_enclosure_data_edit.push({
                                    index: index,
                                    ...res,
                                })
                                let tr = demoListView_edit.find('tr#upload-' + index)
                                    , tds = tr.children()
                                tds.eq(2).html('<span style="color: #5FB878;">上传成功</span>')
                                tds.eq(3).find('.test-upload-demo-reload').addClass('layui-hide')
                                layer.closeAll('loading')
                                return delete this.files[index]
                            } else {
                                layer.msg(res.msg, {
                                    offset: '15px'
                                    , icon: 2
                                    , time: 1000
                                    , id: 'Message',
                                })
                            }
                            layer.closeAll('loading')
                            this.error(index, upload)
                        }
                        , error: function (index, upload) {
                            let tr = demoListView_edit.find('tr#upload-' + index)
                                , tds = tr.children()
                            tds.eq(2).html('<span style="color: #FF5722;">上传失败</span>')
                            tds.eq(3).find('.test-upload-demo-reload').removeClass('layui-hide')
                            layer.closeAll('loading')
                        },
                    })
                    demoListView_edit = $('#order_enclosure_upload_list_edit')
                    order_enclosure_data_edit.push(obj.data)
                    $('#edoc_code_edit').val(`${obj.data.edoc_code},${obj.data.edoc_code_name}`)
                    demoListView_tr_edit = $([
                        '<tr id="upload-' + obj.data.id + '">'
                        ,
                        '<td>' + obj.data.edoc_cop_id + '</td>'
                        ,
                        '<td></td>'
                        ,
                        '<td>已上传</td>'
                        ,
                        '<td>'
                        ,
                        '<button class="layui-btn custom-create_btn test-upload-demo-reload layui-hide" type="button">重传</button>'
                        ,
                        `<button class="layui-btn layui-btn-mini layui-btn-danger test-upload-demo-delete_edit" data-id="${obj.data.id}" type="button">删除</button>`
                        ,
                        '</td>'
                        ,
                        '</tr>'].join(''))
                    demoListView_tr_edit.find('.test-upload-demo-delete_edit').on('click', function () {
                        demoListView_tr_edit.remove()
                        order_enclosure_upload_edit.config.elem.next()[0].value = ''
                        order_enclosure_data_edit.forEach((value, key) => {
                            if ($(this).data('id')) {
                                if (value.id == $(this).data('id')) {
                                    order_enclosure_data_edit.splice(key, 1)
                                }
                            }
                        })
                    })
                    edoc_code = obj.data.edoc_code
                    edoc_code_name = obj.data.edoc_code_name
                    demoListView_edit.append(demoListView_tr_edit)
                    form.render('select')
                    break
                case 'delete':
                    layer.confirm('真的删除么', {title: '提示'}, async (index) => {
                        const data = await admin.delete(`/order/e/pdf/${obj.data.id}`);
                        layer.close(index)
                        if (data.status) {
                            table.reload('order_enclosure_lists')
                        }
                    })
                    break
                case 'recreate':
                    const recreate = await admin.get(`/order/e/${order_id}/pdf/${obj.data.id}/create/recheck_pdf`)
                    layer.msg(recreate.msg)
                    if (recreate.status) {
                        table.reload('order_enclosure_lists')
                    }
                    break
            }
        })
        /**编辑附件**/
        form.on('submit(order_enclosure_submit_edit)', async function (data) {
            if (order_enclosure_data_edit.length === 0) {
                layer.msg('请先上传文件')
            }
            if (order_enclosure_data_edit.length > 1) {
                layer.msg('只能选择一个文件')
                return
            }
            const form_data = {
                edoc_code: edoc_code,
                edoc_code_name: edoc_code_name,
            }
            order_enclosure_data_edit.forEach((value, index) => {
                delete value.status
                delete value.edoc_size
                value.edoc_code = edoc_code
                value.edoc_code_name = edoc_code_name
            })
            const res = await admin.patch(`/order/e/pdf/${order_enclosure_id}/update`, order_enclosure_data_edit[0])
            if (res.status) {
                layer.close(edit_enclosure_index)
                table.reload('order_enclosure_lists')
            }
        })
        /**办理记录**/
        $('body').on('click', '#order_take', async function () {
            if (!order_id) {
                return layer.msg('请先保存订单！')
            }
            layer.load(2)
            const data_order = await admin.get(`/order/e/${order_id}/order_logs`)
            layer.closeAll('loading')
            const data = {
                data_order: data_order,
            }
            laytpl($('#order_take_template').html()).render(data, function (html) {
                $('#order_take_list').html(html)
            })
            layer.open({
                type: 1,
                title: '办理记录',
                shadeClose: true,
                area: admin.screen() < 2 ? ['80%', '300px'] : ['600px', '500px'],
                content: `<div id="order_take_list_content">${$('#order_take_list').html()}</div>`,
            })
        });

        /**申请复核**/
        form.on('submit(order_application_review)', async (data) => {
            if (!isSaved) {
                return layer.msg('请先保存数据')
            }
            if (OrderItemsData.length === 0) {
                return layer.msg('请先输入表体商品')
            }
            if (data.field.NetWt) {
                if (OrderItemsData.length === 0) {
                    return layer.msg('存在净重，必须填写表体商品！')
                }
            }

            const result = await admin.get(`/order/for_recheck/${order_id}`, 'show');
            if (result.status) {
                setTimeout(() => {
                    admin.reloadFrame(iEFlagName + '报关整合申报iframe');
                    statusString = "待复核";
                    admin.getBtnTem("#order_button_template", "#order_button", {
                        statusString: statusString,
                        jq: $,
                    });
                }, 150)
            }

            layer.closeAll('loading')
        });

        /**提交到单一窗口-选择附件**/
        $('body').on('click', '#order_save_reload', async function () {
            try {
                layer.open({
                    type: 1,
                    title: '暂存',
                    shadeClose: true,
                    area: admin.screen() < 2 ? ['80%', '300px'] : ['800px', '600px'],
                    content: $('#order_enclosure_check_template').html(),
                })
                table.render({
                    elem: '#order_enclosure_check_lists'
                    , skin: 'line'
                    , height: 450
                    , url: `/order/e/${order_id}/pdf/lists?sortedBy=desc&orderBy=created_at&is_eco_relations=1`
                    , response: {
                        countName: 'total',
                    }
                    , cols: [
                        [
                            {type: 'checkbox'}
                            , {field: 'edoc_code_name', title: '类型', width: 150}
                            , {field: 'edoc_cop_id', title: '文件名称'}
                            , {title: '操作', toolbar: '#order_enclosure_check_toolbar', width: 180},
                        ]]
                    , page: true
                    , limit: 10,
                })
                form.render()
            } catch (e) {
                return layer.msg('接口错误！', {
                    offset: '15px'
                    , icon: 2
                    , time: 2000
                    , id: 'Message',
                })
            }
        })

        // 提交到单一窗口-附件预览
        table.on('tool(order_enclosure_check_lists)', async function (obj) {
            const data = obj.data
            if (obj.event === 'preview') {
                const preview_data = await admin.get(`/order/e/pdf/${data.id}/show`)
                window.open(preview_data)
            }
        })

        /**提交到单一窗口-提交**/
        $('body').on('click', '#order_enclosure_check', async function () {
            $('#order_save_reload_submit').click()
        })

        /**保存并发送到单一窗口**/
        form.on('submit(order_save_reload_submit)', async (data) => {
            if (OrderItemsData.length === 0) {
                return layer.msg('请先输入表体商品')
            }
            if (data.field.NetWt) {
                if (OrderItemsData.length === 0) {
                    return layer.msg('存在净重，必须填写表体商品！')
                }
            }
            let is_pros = 1
            if (OrderItemsData.length > 0) {
                for (let item of OrderItemsData) {
                    if ((item.g_unit ? item.g_unit != '035' : 1) && (item.first_unit ? item.first_unit != '035' : 1) &&
                        (item.second_unit ? item.second_unit != '035' : 1)) {
                        is_pros = 0
                        break
                    }
                }
            } else {
                is_pros = 0
            }
            if (is_pros) {
                if (!(data.field.NetWt)) {
                    return layer.msg('存在表体商品且是千克，必填净重！')
                }
                let total = 0
                for (let item of OrderItemsData) {
                    if (item.g_unit == '035') {
                        total += parseFloat(item.g_qty) * 100000
                    } else if (item.first_unit == '035') {
                        total += parseFloat(item.first_qty) * 100000
                    } else if (item.second_unit == '035') {
                        total += parseFloat(item.second_qty) * 100000
                    }
                }
                if (admin.cutZero((total / 100000).toString()) != admin.cutZero(data.field.NetWt.toString())) {
                    if (!no_weight_save) {
                        layer.open({
                            title: '商品总重量与净重不符'
                            , content: '商品总重量与净重不符！是否要保存'
                            , btn: ['是', '否']
                            , yes: function (index) {
                                no_weight_save = true
                                layer.close(index)
                                $('#order_save').click()
                            }
                            , btn2: function () {
                                layer.msg('请重新修改净重。')
                                $('#NetWt').focus()
                            },
                        })
                        if (!no_weight_save) {
                            return false
                        }
                    }
                }
            }
            layer.load(2)
            /**企业承诺**/
            data.field.DeclaratioMaterialCode = DeclaratioMaterialCode
            /**其他包装**/
            if (data.field.dec_other_packs) {
                data.field.dec_other_packs = JSON.parse(data.field.dec_other_packs)
            }
            /**企业资质数据**/
            for (let item of OrderEntQualifDeleteIds) {
                EntQualifData.push({
                    id: item,
                })
            }
            data.field.OrderItemLimits = EntQualifData
            /**使用人数据**/
            data.field.dec_users = DecUsersData
            /**表体商品数据**/
            for (let item of OrderQuasVinDeleteIds) {
                OrderItemsData[item.pros_index].OrderItemLimits[item.index].order_pro_qua_vins.push({
                    id: item.id,
                })
            }
            for (let item of OrderQuasDeleteIds) {
                OrderItemsData[item.index].OrderItemLimits.push({
                    id: item.id,
                })
            }
            for (let item of admin.order_pros_delete_ids) {
                OrderItemsData.push({
                    id: item,
                })
            }
            data.field.pros = OrderItemsData
            /**检验检疫申报要素数据**/
            data.field.dec_request_certs = DecRequestCertsData.checkData || []
            data.field.DomesticConsigneeEname = DecRequestCertsData.DomesticConsigneeEname
            data.field.OverseasConsignorCname = DecRequestCertsData.OverseasConsignorCname
            data.field.OverseasConsignorAddr = DecRequestCertsData.OverseasConsignorAddr
            data.field.CmplDschrgDt = DecRequestCertsData.CmplDschrgDt

            data.field.containers = OrderContainers
            /**随附单证数据**/
            for (let item of admin.order_documents_delete_ids) {
                OrderDocuments.push({
                    id: item,
                })
            }
            data.field.documents = OrderDocuments
            /**业务选项**/
            data.field.promise_itmes = []
            /**特殊关系确认**/
            if (!(data.field['promise_itmes[0]'])) {
                if ($('#promise_itmes0').data('first') == '1') {
                    data.field.promise_itmes.push('0')
                } else {
                    data.field.promise_itmes.push('9')
                }
            } else {
                delete data.field['promise_itmes[0]']
                data.field.promise_itmes.push('1')
            }
            /**价格影响确认**/
            if (!(data.field['promise_itmes[1]'])) {
                if ($('#promise_itmes1').data('first') == '1') {
                    data.field.promise_itmes.push('0')
                } else {
                    data.field.promise_itmes.push('9')
                }
            } else {
                delete data.field['promise_itmes[1]']
                data.field.promise_itmes.push('1')
            }
            /**支付特权使用费确认**/
            if (!(data.field['promise_itmes[2]'])) {
                if ($('#promise_itmes2').data('first') == '1') {
                    data.field.promise_itmes.push('0')
                } else {
                    data.field.promise_itmes.push('9')
                }
            } else {
                delete data.field['promise_itmes[2]']
                data.field.promise_itmes.push('1')
            }
            /**异地报关**/
            if ($('#is_other').prop('checked')) {
                data.field.is_other = 1
            } else {
                data.field.is_other = 0
            }
            data.field.id = order_id
            data.field.order_status = '单一处理中'
            const data_table = table.checkStatus('order_enclosure_check_lists').data
            const edoc_codes = data_table.map((item) => item.edoc_code)
            const decl_trn_rel = $('#decl_trn_rel').prop('checked') ? 1 : 0
            data.field.edoc_codes = edoc_codes
            data.field.decl_trn_rel = decl_trn_rel
            const order_save_data = await admin.post(`/order/e/re_create_xml`, data.field)
            setTimeout(() => {
                layer.closeAll()
            }, 2000)
        })

        //表单验证规则
        let formVer = {
            DistinatePortName(value, item) {
                if (value.trim()) {
                    const i_e_port = $('#IEPort').val()
                    const distinate_port = $('#DistinatePort').val()
                    if (!(value.trim())) {
                        return '请输入经停港!'
                    }
                    if (i_e_port == '5301' || i_e_port == '5320' || i_e_port == '5303' || i_e_port == '5345') {
                        if (distinate_port != 'HKG003') {
                            return '经停港必须为HKG003'
                        }
                    }
                }
            },
            TradeCountryName(value, item) {
                if (!isCreate() && !(value.trim())) {
                    return layer.msg('请填写运抵/启运国(地区)')
                }
            },
            IEPortName(value, item) {
                if (!(value.trim())) {
                    return layer.msg('请填写出境关别')
                }
            },
            gross_wet(value, item) {
                if (!isCreate()) {
                    if (isNaN(value.trim())) {
                        return '毛重不足1，按1填报'
                    } else if (value.trim() < '1') {
                        return '毛重不足1，按1填报'
                    }
                }
            },
            net_wt(value, item) {
                if (!isCreate()) {
                    if (!(value.trim())) {
                        return '请填写净重'
                    } else if (parseFloat(value.trim()) > parseFloat($('#GrossWet').val().trim())) {
                        return '净重大于毛重，请确认后重新填写!'
                    }
                }
            },
            TrafModeName(value, item) {
                const i_e_port = $('#IEPort').val()
                const traf_mode = $('#TrafMode').val()
                if (!isCreate() && !(value.trim())) {
                    return '请输入运输方式!'
                }
                if (i_e_port == '5301' || i_e_port == '5320' || i_e_port == '5303' || i_e_port == '5345') {
                    if (traf_mode != '4') {
                        return '运输方式必须为公路运输'
                    }
                }
            },
            enty_port_name(value, item) {
                const i_e_port = $('#IEPort').val()
                const enty_port_code = $('#EntyPortCode').val()
                if (!isCreate() && !(value.trim())) {
                    return '请输入（入/出境口岸）!'
                }
                if (i_e_port == '5301') {
                    if (enty_port_code != '470201') {
                        return '入/出境口岸必须为470201'
                    }
                }
                if (i_e_port == '5320') {
                    if (enty_port_code != '470401') {
                        return '入/出境口岸必须为470401'
                    }
                }
                if (i_e_port == '5303') {
                    if (enty_port_code != '470501') {
                        return '入/出境口岸必须为470501'
                    }
                }
                if (i_e_port == '5304') {
                    if (!(enty_port_code == '470101' || enty_port_code == '470102' || enty_port_code == '471801')) {
                        return '入/出境口岸必须为470101或者471801或者470102'
                    }
                }
                if (i_e_port == '5316') {
                    if (enty_port_code != '470601') {
                        return '入/出境口岸必须为470601'
                    }
                }
            },
        }
        /**表单验证规则**/
        form.verify(formVer);
        /** 一般贸易禁止输入备案序号 **/
        $(CheckManualNo())
        $('#ManualNo').bind('input propertychange', function () {
            CheckManualNo()
        })

        function CheckManualNo() {
            if (!$('#ManualNo').val()) {
                $('#ContrItem').attr('disabled', 'disabled')
                $('#ContrItem').val('')
                form.render()
                return
            }
        }

        //判断是否是代客下单
        function isCreate() {
            return !statusString || $.inArray(statusString, ['待审核', '审核中', '审核通过', '审核不通过']) >= 0
        }

        // 置空集装箱/随附单证数据
        function setOrderRelationEmpty(obj) {
            $(`#${obj.formID} input`).each(function () {
                $(this).val('')
            });
            $(`#${obj.focusId}`).focus();
            if (obj.datas) {
                layui.table.reload(obj.tableName, {
                    data: obj.datas,
                    limit: obj.datas.length,
                });
            }

            obj.index = null
        }

        // 置空表体表单数据
        function setOrderItemEmptyData(is_order_item_insert) {
            /**产品**/
            admin.getOrderTable(OrderItemsData, ieflag)
            $('#order_pros_form input').each(function () {
                if ($(this).attr('id') == 'GNo') {
                    $(this).val(OrderItemsData.length + 1)
                } else {
                    if (!($(this).is('[no_empty]'))) {
                        $(this).val('')
                    }
                }
            })

            OrderItemGoodsAttr = []
            /**表体货物属性**/
            OrderItemGoodsAttrName = []
            /**表体货物属性名称**/
            //  检验检疫货物规格 临时数据
            OrderItemStuff = ''
            OrderItemProdValidDt = ''
            OrderItemProdQgp = ''
            OrderItemEngManEntCnm = ''
            OrderItemGoodsSpec = ''
            OrderItemGoodsModel = ''
            OrderItemGoodsBrand = ''
            OrderItemProduceDate = ''
            OrderItemProdBatchNo = ''

            // 危险货物信息
            OrderItemNoDangFlag = ''
            OrderItemNoDangFlagName = ''
            OrderItemDangName = ''
            OrderItemUnCode = ''
            OrderItemDangPackType = ''
            OrderItemDangPackTypeName = ''
            OrderItemDangPackSpec = ''
            OrderItemDangPackSpecName = ''
            OrderItemLimits = []  // 货物申报产品资质

            if ($('#ContrItem').is(':disabled')) {
                $('#CodeTS').focus()
            } else {
                $('#ContrItem').focus()
            }
            admin.is_total_number(OrderItemsData)
            /**tip:总价/成交数量合计/法定第一数量合计/法定第二数量合计**/
            orderItemIndex = null;
            isOrderItemInsert = false;
        }

        // 集装箱
        function renderContainerTable() {
            table.render({
                elem: '#order_containers_table'
                , toolbar: '#order_containers_tool'
                , defaultToolbar: ['filter']
                , colFilterRecord: 'local'
                , cols: [
                    [
                        {type: 'checkbox'}
                        , {field: 'ContainerId', title: '集装箱号', width: 120}
                        , {field: 'ContainerMdName', title: '集装箱规格', width: 150}
                        , {field: 'LclFlagName', title: '拼箱标识', width: 120},
                    ]]
                , data: OrderContainers
                , limit: OrderContainers.length
                , height: 200,
            });
        }

        // 随附单证
        function renderDocTable() {
            table.render({
                elem: '#order_documents_table'
                , toolbar: '#order_documents_tool'
                , defaultToolbar: ['filter']
                , colFilterRecord: 'local'
                , cols: [
                    [
                        {type: 'checkbox'}
                        , {field: 'DocuCode', title: '单证代码', width: 120}
                        , {field: 'CertCode', title: '单证编号'},
                    ]]
                , data: OrderDocuments
                , limit: OrderDocuments.length
                , height: 200,
            })
        }

    })
</script>